lua脚本操作Redis

一次扣减一个商品库存

@Component

public class LuaDemo {

@Autowired
private StringRedisTemplate redisTemplate;


public void test() {

  List<String> keys = new ArrayList<>();
    keys.add("yanjie007");

    String lua = "return redis.call('set',KEYS[1],ARGV[1])";

    RedisScript<String> redisScript=  RedisScript.of(lua,String.class);

    String shuai = stringRedisTemplate.execute(redisScript, keys, "今天真帅");

    System.out.println(shuai);

}

}

//扣减库存

@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 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();
}

一次扣减多个商品的库存

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);


}
相关推荐
Hello.Reader32 分钟前
Redis热点数据管理全解析:从MySQL同步到高效缓存的完整解决方案
redis·mysql·缓存
C++忠实粉丝2 小时前
Redis 介绍和安装
数据库·redis·缓存
ClouGence3 小时前
Redis 到 Redis 数据迁移同步
数据库·redis·缓存
苏三说技术3 小时前
Redis 性能优化的18招
数据库·redis·性能优化
Tttian6224 小时前
基于Pycharm与数据库的新闻管理系统(2)Redis
数据库·redis·pycharm
言之。4 小时前
redis延迟队列
redis
hanbarger5 小时前
nosql,Redis,minio,elasticsearch
数据库·redis·nosql
弗罗里达老大爷6 小时前
Redis
数据库·redis·缓存
DT辰白20 小时前
基于Redis的网关鉴权方案与性能优化
数据库·redis·缓存
木子七21 小时前
Redis-十大数据类型
redis