场景一:出入库存量——分布锁
- 锁是共享的
- Callable回调返回结果会抛出异常。Runable不会抛出异常
- k打进去==能获取到锁
- 自定义线程
- mysql并发超过2000就会跟慢,要把压力传给给Redis。这样的场景有秒杀、
场景二:秒杀
lua脚本是将string转换成二进制。转换成二进制之前,数字要先强转成数字;且使用多行lua脚本使用stringBuilder()方法;双引号加空号,符号加空格;否则两个单词会默认成一个,识别不了
1 @SpringBootTest 2 public class DockerTest { 3 @Resource(name="redisTemplate") 4 private ValueOperations<String,Integer> valueOperations; 5 @Autowired 6 private StringRedisTemplate stringRedisTemplate; 7 @Test //初始化 Redis库存量 8 void test() throws IOException { 9 valueOperations.set("producthh",20); 10 } 11 12 @Test 13 void Test111() throws IOException { 14 ExecutorService executorService = Executors.newCachedThreadPool(); 15 StringBuilder letter = new StringBuilder(); 16 letter.append(" local qty1 = redis.call('get',KEYS[1]) "); 17 letter.append(" local qty2 = ARGV[1] "); 18 letter.append(" if (tonumber(qty1) >= tonumber(qty2)) "); 19 letter.append(" then "); 20 letter.append(" redis.call('decrby',KEYS[1],qty2) "); 21 letter.append(" return -1 "); 22 letter.append(" else "); 23 letter.append(" return tonumber(qty1) "); 24 letter.append(" end "); 25 RedisScript<Long> script = RedisScript.of(letter.toString(), Long.class); 26 for (int i = 1; i < 10; i++) { 27 int finalI = i; 28 executorService.execute(() -> { 29 int qty = RandomUtil.randomInt(1, 20); 30 Long ret = stringRedisTemplate.execute(script, CollUtil.newArrayList(key), String.valueOf(qty)); 31 if (ret == -1) { 32 System.out.println(finalI + "扣减成功->" + qty); 33 } else { 34 System.out.println("失败,需要:" + qty + " 剩余库存:" + ret); 35 } 36 }); 37 38 39 } 40 41 ThreadUtil.safeSleep(10000); 42 43 44 } 45 46 }
标签:场景,20,springboot,Redis,qty,letter,append From: https://www.cnblogs.com/liang9479/p/17226975.html