当前位置:网站首页>Redis spike case, learn from Shang Silicon Valley teacher in station B
Redis spike case, learn from Shang Silicon Valley teacher in station B
2022-07-27 03:29:00 【Attacking polar bear】
One 、 Use redis To solve the seckill problem , But there will be inventory problems
Two 、 Use lua Script solves the seckill problem
0、 Use lua The advantages of scripting

1、 Specific use of service Layer code
package com.bear.service;
import com.bear.config.JedisPoolUtil;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.IOException;
/** * < sketch > * < Detailed description > * * @author LiuShanshan * @version $Id$ */
@Service
public class SewckillServiceTwo {
String secKillScript ="local userid=KEYS[1];\r\n" +
"local prodid=KEYS[2];\r\n" +
"local qtkey='sk:'..prodid..\":qt\";\r\n" +
"local usersKey='sk:'..prodid..\":usr\";\r\n" +
"local userExists=redis.call(\"sismember\",usersKey,userid);\r\n" +
"if tonumber(userExists)==1 then \r\n" +
" return 2;\r\n" +
"end\r\n" +
"local num= redis.call(\"get\" ,qtkey);\r\n" +
"if tonumber(num)<=0 then \r\n" +
" return 0;\r\n" +
"else \r\n" +
" redis.call(\"decr\",qtkey);\r\n" +
" redis.call(\"sadd\",usersKey,userid);\r\n" +
"end\r\n" +
"return 1" ;
public boolean doSecKill(String prodid,String uid) throws IOException {
JedisPool jedispool = JedisPoolUtil.getJedisPoolInstance();
Jedis jedis=jedispool.getResource();
//String sha1= .secKillScript;
String sha1= jedis.scriptLoad(secKillScript);
Object result= jedis.evalsha(sha1, 2, uid,prodid);
String reString=String.valueOf(result);
if ("0".equals( reString ) ) {
System.err.println(" Empty !!");
}else if("1".equals( reString ) ) {
System.out.println(" Panic buying !!!!");
}else if("2".equals( reString ) ) {
System.err.println(" The user has robbed !!");
}else{
System.err.println(" Panic buying exception !!");
}
jedis.close();
return true;
}
}
2、controller layer
/** * Seckill test use lua Script * @return */
@GetMapping("/seckill/test")
public Boolean seckillTest() throws IOException {
// Fixed goods id ;// Automatically generated users id
return sewckillServiceTwo.doSecKill("1001", Long.toString(System.currentTimeMillis()));
}
边栏推荐
猜你喜欢
随机推荐
PIP3 setting alicloud
30分钟彻底弄懂 synchronized 锁升级过程
Detailed explanation of const usage in C language
基于OpenCV的轮廓检测(1)
阿里 Seata 新版本终于解决了 TCC 模式的幂等、悬挂和空回滚问题
typescript ts 基础知识之接口、泛型
A new paradigm of distributed deep learning programming: Global tensor
Technology vane | interpretation of cloud native technology architecture maturity model
spark:地区广告点击量排行统计(小案例)
榕树贷款,
Add support for @data add-on in idea
阶乘末尾0的数量
pip3 设置阿里云
DTS搭载全新自研内核,突破两地三中心架构的关键技术|腾讯云数据库
二叉树(北京邮电大学机试题)(DAY 85)
“满五唯一”和“满二唯一”是什么?有什么不同?
2022牛客多校第二场的J -- 三分做法
[learning notes, dog learning C] string + memory function
[flask] the server obtains the file requested by the client
带你了解什么是 Web3.0







![[1206. Design skip table]](/img/a9/ca45c9fedd6e48387821bdc7ec625c.png)