public class RedisLua { public static final String STOCK_LUA; Static {/** * inventory reduction Lua script (inventory reduction one at a time) * KEYS[1]: item quantity key * KEYS[2]: order key * ARGV[1]: order information * -1: low inventory * -2: double order * */ StringBuilder sb = new StringBuilder(); sb.append("local goodsKey = KEYS[1];" ); sb.append("local orderKey = KEYS[2];" ); sb.append("local orderValue = ARGV[1];" ); sb.append("local goodsNum = redis.call('get', goodsKey);" ); sb.append("local order = redis.call('get', orderKey);" ); sb.append("if goodsNum < '1' then"); sb.append(" return -1;" ); sb.append("end;" ); sb.append("if order == false then"); sb.append(" redis.call('set', orderKey , orderValue);" ); sb.append(" return redis.call('decrBy', goodsKey, '1');" ); sb.append("else"); sb.append(" return -2;" ); sb.append("end;" ); STOCK_LUA = sb.toString(); /** * Subtract inventory Lua script (subtract multiple inventories at once) * KEYS[1]: quantity of item Key * KEYS[2]: order key * ARGV[1]: Subtract quantity * ARGV[2]: order information * -1: low stock * -2: repeat order * */ *StringBuilder sb = new StringBuilder(); sb.append("local goodsKey = KEYS[1];" ); sb.append("local orderKey = KEYS[2];" ); sb.append("local decrNum = ARGV[1];" ); sb.append("local orderValue = ARGV[2];" ); sb.append("local goodsNum = redis.call('get', goodsKey);" ); sb.append("local order = redis.call('get', orderKey);" ); sb.append("if goodsNum < decrNum then"); sb.append(" return -1;" ); sb.append("end;" ); sb.append("if order == false then"); sb.append(" redis.call('set', orderKey , orderValue);" ); sb.append(" return redis.call('decrBy', goodsKey, decrNum);" ); sb.append("else"); sb.append(" return -2;" ); sb.append("end;" ); STOCK_LUA = sb.toString(); * /}} to useCopy the code
Execute the lua script using redisTemplate
List<String> keys = Arrays.asList("goodsKey:85265602","OrderKey:457811515"); String [] arg = {"1232555"}; DefaultRedisScript<Long> stringDefaultRedisScript = new DefaultRedisScript<>(); stringDefaultRedisScript.setResultType(Long.class); stringDefaultRedisScript.setScriptText(STOCK_LUA); / / the corresponding script text STOCK_LUA Long res = redisTemplate. Execute (stringDefaultRedisScript, keys, arg);Copy the code