lua脚本操作Redis

lua脚本操作Redis

一次扣减一个商品库存

java 复制代码
**  //扣减库存
 @Test
    void test2() throws IOException {
        valueOperations.set(key,15L);
        StringBuilder sb = new StringBuilder();
        sb.append(" local key = KEYS[1]  ");
        sb.append(" local qty = ARGV[1]  ");
        sb.append(" local redis_qty = redis.call('get',key)  ");
        sb.append(" if tonumber(redis_qty) >= tonumber(qty) then  ");
        sb.append("   redis.call('decrby',key,qty) ");
        sb.append("  return  -1  ");
        sb.append(" else  ");
        sb.append("  return tonumber(redis_qty) ");  //  0, 1,2,3 ....
        sb.append(" end  ");
        sb.append("   ");
        RedisScript<Long> script = RedisScript.of(sb.toString(),Long.class);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.execute(()->{
                int needQty = RandomUtil.randomInt(1, 5);
                Long qty =  stringRedisTemplate.execute(script, CollUtil.newArrayList(key), needQty+"");
             if(qty.intValue() == -1 ){
                 System.out.println("线程"+ finalI +"扣减成功,需求量是:"+needQty);
              } else {

                 System.out.println("线程"+ finalI +"扣减失败,当前库存变量是:"+qty);
             }
            });
        }


        System.in.read();
    }

一次扣减多个商品的库存

java 复制代码
void test4()  {

        StringBuilder sb = new StringBuilder();
        sb.append(" local table = {}  "); // 你要扣减的key :product.1
        sb.append(" local values =  redis.call('mget',  unpack(KEYS) )"); // [product.1,product.2]   =>  product.1 product.2
        sb.append(" for i = 1, #KEYS   do  ");
        sb.append("   if  tonumber(ARGV[i]) > tonumber(values[i])   then ");
        sb.append("     table[#table + 1] =  KEYS[i] .. '=' .. values[i] "); // product.1=23
        sb.append("   end ");
        sb.append(" end ");
        sb.append(" if #table > 0 then ");
        sb.append("   return table  ");
        sb.append(" end ");
        sb.append(" for i = 1 , #KEYS do ");
        sb.append("   redis.call('decrby',KEYS[i],ARGV[i])  ");
        sb.append(" end ");
        sb.append(" return {} ");
        RedisScript<List> luaScript = RedisScript.of(sb.toString(), List.class);

          List<StockProduct> stockProducts =  new ArrayList<>();
          stockProducts.add(new StockProduct(5,1));
          stockProducts.add(new StockProduct(4,2));

        List<String> keys = stockProducts.stream().map(it -> "product." + it.getId()).collect(Collectors.toList());
        Object[] qtys = stockProducts.stream().map(it -> it.getQty() + "").toArray();
        List<String> list = stringRedisTemplate.execute(luaScript,
                keys,
                qtys);
        if(list.isEmpty()){
            System.out.println("库存冻结成功");
        } else {

            for (String key_qty : list) {
                String[] split = key_qty.split("=");
                System.out.println(split[0] + "库存不足,剩余库存量:" + split[1]);
            }

        }


        ThreadUtil.safeSleep(3000);


    }
相关推荐
_.Switch16 分钟前
Python 自动化运维持续优化与性能调优
运维·开发语言·python·缓存·自动化·运维开发
徐*红16 分钟前
java 线程池
java·开发语言
尚学教辅学习资料16 分钟前
基于SSM的养老院管理系统+LW示例参考
java·开发语言·java毕设·养老院
1 9 J18 分钟前
Java 上机实践4(类与对象)
java·开发语言·算法
Code apprenticeship19 分钟前
Java面试题(2)
java·开发语言
J不A秃V头A22 分钟前
Python爬虫:获取国家货币编码、货币名称
开发语言·爬虫·python
FIN技术铺3 小时前
Redis集群模式之Redis Sentinel vs. Redis Cluster
数据库·redis·sentinel
SRY122404193 小时前
javaSE面试题
java·开发语言·面试
无尽的大道3 小时前
Java 泛型详解:参数化类型的强大之处
java·开发语言
ZIM学编程3 小时前
Java基础Day-Sixteen
java·开发语言·windows