StringBuilder sb = new StringBuilder();
sb.append(" local table = {} ");
sb.append(" local values = redis.call('mget', unpack(KEYS) )");
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] ");
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);
sb2.append("for i = 1, #KEYS do ")
.append(" redis.call('incrby', KEYS[i], ARGV[i]) ")
.append("end ")
.append("return 'ok' ");
public String increase(List<DecreaseRequest> decreaseRequests) {
RedisScript<String> luaScript = RedisScript.of(sb2.toString(), String.class);
List<String> keys = decreaseRequests.stream()
.map(it -> redisInventory + it.getProductId())
.collect(Collectors.toList());
List<String> quantities = decreaseRequests.stream()
.map(DecreaseRequest::getCount)
.map(Object::toString)
.collect(Collectors.toList());
String[] values = ArrayUtil.toArray(quantities, String.class);
String result = stringRedisTemplate.execute(luaScript, keys, values);
if ("ok".equals(result)) {
decreaseRequests.forEach(it -> {
log.debug("订单 {} 回补库存成功,商品 ID:{},商品名称:{},回补数量为:{}", it.getOrderId(), it.getProductId(), it.getProductName(), it.getCount());
});
return result;
} else {
log.error("库存回补失败");
}
return "error";
}