当前位置:网站首页>Redis seckill demo
Redis seckill demo
2022-07-01 15:35:00 【y_ w_ x_ k】
Scheme 1 : Method plus synchronized that will do , Thread safety scheme , But the efficiency of execution is low , Not suitable for large concurrent occasions
Option two : Use optimistic lock
controller:
@RestController
public class SecondKill {
@Autowired
SecondKillSev secondKillSev;
@RequestMapping(value = "/buy",method = RequestMethod.POST)
public Mes buy(@RequestParam("proid") String proid){
String usedId=new Random().nextInt(1000)+"";
Mes mes = secondKillSev.doSecondKill(usedId, proid);
return mes;
}
}service:
@Service
public class SecondKillSev {
Mes message;
public SecondKillSev(){
}
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* Execute seckill
* Scheme 1 :synchronized, Thread safety , But the efficiency of execution is low , Not suitable for large concurrent occasions
* Option two : Monitor transactions with optimistic locks
*/
public Mes doSecondKill(String uid, String proid){
//1. Judge uid and proid Non empty
if(uid==null || proid==null){
return Mes.getMes("400","uid and proid Can't be empty ");
}
//2. Connect redis
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//3. Splicing key, stock key, Successful user key
String kcKey="kcKey:"+proid;
String userKey="userKey:"+proid;
// Optimistic lock solves oversold problem
//stringRedisTemplate The default is not to open things
stringRedisTemplate.setEnableTransactionSupport(true);
List<Object> txResults = stringRedisTemplate.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
// Monitor inventory
operations.watch(kcKey);
//4. Get inventory , If the inventory is null, The second kill has not yet started
String kc=ops.get(kcKey);
if(kc==null){
message= Mes.getMes("400"," The stock is null, The second kill hasn't started yet ");
return null;
}
//5. Judge whether the user repeats the second kill
if(operations.opsForSet().isMember(userKey, uid)){
message=Mes.getMes("400"," You can't repeat the second kill ");
return null;
}
//6. Judge the quantity of goods , If the quantity is less than 1, Then the second kill is over
if(Integer.parseInt(kc)<=0){
message=Mes.getMes("400"," The second kill is over ");
return null;
}
//7. Second kill process , stock -1, Successful user added to manifest
// With a transaction
operations.multi();
operations.opsForValue().decrement(kcKey);
operations.opsForSet().add(userKey,uid);
List exec = operations.exec();
if(exec==null || exec.size()==0){
message=Mes.getMes("400"," Seckill failure ");
return null;
}else{
return exec;
}
}
});
if(txResults==null ||txResults.size()==0){
return message;
}
return Mes.getMes("200"," Seckill success ");
}
}
But this scheme also has a disadvantage , That is, if the quantity of goods is 500, But the number of threads is 1000, That is, when the number of visits is not very large , There will be the problem that the inventory is not sold out , That is, inventory leftover problems , So it can be used lua Script to solve ;
Option three :lua Script
local userid=KEYS[1];
local prodid=KEYS[2];
local qtkey="sk:"..prodid..":qt";
local userskey="sk:"..prodid..":user";
local userExists=redis.call("sismember",userskey,userid);
if tonumber(userExists)==1 then
return 2;
end
local num=redis.call("get",qtkey);
if tonumber(num)<=0 then
return 0;
else
redis.call("decr",qtkey);
redis.call("sadd",userskey,userid);
end
return 1
Code implementation :
@Service
public class SeckillByScript {
static String secKillScript1 = "local userid=KEYS[1];\n" +
"local prodid=KEYS[2];\n" +
"local qtkey=\"sk:\"..prodid..\":qt\";\n" +
"local userskey=\"sk:\"..prodid..\":user\";\n" +
"local userExists=redis.call(\"sismember\",userskey,userid);" +
"if tonumber(userExists)==1 then\n" +
" return 2;\n" +
"end\n" +
"local num=redis.call(\"get\",qtkey);\n" +
"if tonumber(num)<=0 then\n" +
" return 0;\n" +
"else\n" +
" redis.call(\"decr\",qtkey);\n" +
" redis.call(\"sadd\",userskey,userid);\n" +
" end\n" +
" return 1";
public boolean doSecKill(String userid, String prodid) {
JedisPool jedisPool = JedisPoolUtil.getJedisPool();
Jedis jedis = jedisPool.getResource();
String sha1 = jedis.scriptLoad(secKillScript1);
Object result = jedis.evalsha(sha1, 2, userid, prodid);
String reString = String.valueOf(result);
if ("0".equals(reString)) {
System.out.println(" Empty !");
return false;
} else if ("1".equals(reString)) {
System.out.println(" Panic buying ");
return true;
} else if ("2".equals(reString)) {
System.out.println(" The user has robbed !");
return false;
} else {
System.out.println(" Panic buying exception ");
return false;
}
}
}
边栏推荐
- 如何实现时钟信号分频?
- Qt+pcl Chapter 9 point cloud reconstruction Series 2
- Can I choose to open an account on Great Wall Securities? Is it safe?
- Recommendation of data acquisition tools and detailed graphic process of data acquisition list
- skywalking 6.4 分布式链路跟踪 使用笔记
- The difference between arrow function and ordinary function in JS
- 榨汁机UL982测试项目有哪些
- [target tracking] |stark
- [lock] redis lock handles concurrency atomicity
- 【STM32学习】 基于STM32 USB存储设备的w25qxx自动判断容量检测
猜你喜欢

S32K1xx 微控制器的硬件設計指南
![[advanced ROS] lesson 5 TF coordinate transformation in ROS](/img/4d/ae7d477bf6928005e16f046d461dcb.png)
[advanced ROS] lesson 5 TF coordinate transformation in ROS
![[leetcode] 16. The sum of the nearest three numbers](/img/60/6a68333d6e543c601e6ed586b830d0.png)
[leetcode] 16. The sum of the nearest three numbers

Wechat official account subscription message Wx open subscribe implementation and pit closure guide

Photoshop plug-in HDR (II) - script development PS plug-in

微信公众号订阅消息 wx-open-subscribe 的实现及闭坑指南

做空蔚来的灰熊,以“碰瓷”中概股为生?
![[one day learning awk] function and user-defined function](/img/e1/a378211ef05fcc4d469363f3e509a7.png)
[one day learning awk] function and user-defined function

Guide de conception matérielle du microcontrôleur s32k1xx

《性能之巅第2版》阅读笔记(五)--file-system监测
随机推荐
《QT+PCL第六章》点云配准icp系列3
Introduction to MySQL audit plug-in
What are the EN ISO 20957 certification standards for common fitness equipment
【一天学awk】函数与自定义函数
TS reports an error don't use 'object' as a type The `object` type is currently hard to use
Sort out the four commonly used sorting functions in SQL
微信小程序03-文字一左一右显示,行内块元素居中
Qt+pcl Chapter 6 point cloud registration ICP series 3
MySQL审计插件介绍
张驰咨询:锂电池导入六西格玛咨询降低电池容量衰减
做空蔚来的灰熊,以“碰瓷”中概股为生?
Summary of empty string judgment in the project
[lock] redis lock handles concurrency atomicity
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(三)
Short Wei Lai grizzly, to "touch China" in the concept of stocks for a living?
华为发布HCSP-Solution-5G Security人才认证,助力5G安全人才生态建设
点云重建方法汇总一(PCL-CGAL)
Shopping mall 6.27 to be completed
Qt+pcl Chapter 6 point cloud registration ICP Series 2
leetcode:329. Longest increasing path in matrix