lua脚本操作Redis

news/2025/3/28 8:17:52/

lua脚本操作Redis

一次扣减一个商品库存

**  //扣减库存@Testvoid 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();}

一次扣减多个商品的库存

void test4()  {StringBuilder sb = new StringBuilder();sb.append(" local table = {}  "); // 你要扣减的key :product.1sb.append(" local values =  redis.call('mget',  unpack(KEYS) )"); // [product.1,product.2]   =>  product.1 product.2sb.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=23sb.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);}

http://www.ppmy.cn/news/1401586.html

相关文章

FastAPI+React全栈开发14 FastAPI如何开发REST接口

Chapter03 Getting Started with FastAPI 14 How does FastAPI speak REST FastAPIReact全栈开发14 FastAPI如何开发REST接口 Let’s create a minial FastAPI application, a classic Hello World example, and start examining how FastAPI structures the endpoints. I u…

QT:如何在程序密集响应时,界面不会卡住?

前因&#xff1a; 当调用QApplication::exec()时&#xff0c;就启动了QT的事件循环。在开始的时候QT会发出一些事件命令来显示和绘制窗口部件。 在这之后&#xff0c;事件循环就开始运行&#xff0c;它不断检查是否有事件发生并且把这些事件发生给应用程序的QObject。 当处理…

npm mongoose包下载冲突解决之道

我在新电脑下载完项目代码后,运行 npm install --registryhttps://registry.npm.taobao.org 1运行就报错&#xff1a; npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: lowcode-form-backend1.0.0 npm …

gpt-llm-trainer 出炉

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

基于SSM的戒烟网站(有报告)。Javaee项目。ssm项目。

演示视频&#xff1a; 基于SSM的戒烟网站&#xff08;有报告&#xff09;。Javaee项目。ssm项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结构&#xff0c;通过Spring SpringMv…

Unity构建详解(5)——SBP的Bundle组装

【Bundle的组成】 Bundle里包含Asset、Asset由Object组成&#xff0c;Object由Type组成。前文说了Type由MonoScript的方式处理&#xff0c;这里我们需要从Object看起。 Asset由Object组成&#xff0c;Object可能依赖其他Asset中的Object&#xff0c;Asset之间的依赖本质是由O…

Go-React做一个todolist(服务端)【一】项目初始化

后端仓库地址 地址 项目依赖 # gin go get -u github.com/gin-gonic/gin # viper日志 go get -u github.com/spf13/viper # 数据库和gorm go get -u gorm.io/driver/mysql go get -u gorm.io/gorm # uuid go get -u github.com/google/uuid # token go get -u github.com/go…

Gitea 的详细介绍

什么是 Gitea&#xff1f; Gitea 是一个开源、轻量级的自托管 Git 服务&#xff0c;它允许用户搭建类似于 GitHub 或 GitLab 的代码托管平台。由于采用 Go 语言开发&#xff0c;Gitea 具有高效的性能和跨平台特性&#xff0c;适合个人开发者或小团队使用。 Gitea 的特点 轻量…