@SpringBootTest
public class MyluaTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Resource(name = "redisTemplate")
private ValueOperations valueOperations;
@Test
void test() {
valueOperations.set("pi1", 14);
valueOperations.set("pi2", 11);
valueOperations.set("pi3", 6);
}
@Test
void test1() {
ArrayList<MyProduct> myProDucts1 = CollUtil.newArrayList(new MyProduct().setProductId("pi1").setQty(14),
new MyProduct().setProductId("pi2").setQty(11),
new MyProduct().setProductId("pi3").setQty(6)
);
StringBuilder sb = new StringBuilder();
//查看商品id的库存实际数量
sb.append(" local redisQtys = redis.call('mget',unpack(KEYS)) ");
sb.append(" local myTable = {} ");
sb.append(" for i = 1, #KEYS do ");
//判断若需求量大于库存量,把商品id和库存量放入myTable数组.否则不做操作
sb.append(" if tonumber(ARGV[i]) > tonumber(redisQtys[i]) then ");
sb.append(" myTable[#myTable + 1] = KEYS[i] .. '=' .. tonumber(redisQtys[i]) ");
sb.append(" end ");
sb.append(" end ");
//如果myTable不为空,则返回库存不足,显示出商品id和库存数量
sb.append(" if #myTable > 0 then ");
sb.append(" return myTable ");
sb.append(" end");
//如果myTable为空,则做减库存.出库操作,返回空数组,
sb.append(" for i=1, #KEYS do");
sb.append(" redis.call('decrby',KEYS[i],ARGV[i]) ");
sb.append(" end ");
sb.append(" return {}");
RedisScript<List> script = RedisScript.of(sb.toString(), List.class);
List<String> keys = myProDucts1.stream().map(it -> it.getProductId()).collect(Collectors.toList());
Object[] qtys = myProDucts1.stream().map(it -> it.getQty()+"").toArray();
List list = stringRedisTemplate.execute(script, keys, qtys);
if (list.isEmpty()) {
System.out.println(StrUtil.format("下单成功"));
} else {
System.out.println(StrUtil.format("下单失败,{}", list));
}
}
}
测试类
@Data
@Accessors(chain = true)
public class MyProduct {
private String productId;
private Integer qty;
}
只有+""才能是 arg...