package spring;
import org.redisson.Redisson;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import java.util.ArrayList;
import java.util.List;
import static org.redisson.api.RScript.Mode.READ_WRITE;
/**
public class Console {
public static void main(String[] args) { Config config = new Config(); config.setLockWatchdogTimeout(10000); config.useSingleServer().setAddress("redis://127.0.0.1:36379"); RedissonClient redissonClient = Redisson.create(config); //扣减库存 List<Object> keys = new ArrayList<>(); keys.add("txk"); Object[] values=new Object[]{1}; Object eval = redissonClient.getScript().eval(READ_WRITE, RedisLua.REDUCE_INVENTORY, RScript.ReturnType.INTEGER, keys, values); System.out.println(eval); //添加库存 List<Object> keys1 = new ArrayList<>(); keys1.add("txk"); Object[] values1=new Object[]{10}; Object eval1 = redissonClient.getScript().eval(READ_WRITE, RedisLua.ADD_INVENTORY, RScript.ReturnType.INTEGER, keys1, values1); System.out.println(eval1); } static class RedisLua { public static final String REDUCE_INVENTORY; public static final String ADD_INVENTORY; static { /** * @params 库存key * @return * -4:代表库存传进来的值是负数(非法值) * -3:库存未初始化 * -2:库存不足 * -1:库存为0 * 大于等于0:剩余库存(扣减之后剩余的库存) */ StringBuilder sb = new StringBuilder(); sb.append("if (redis.call('exists', KEYS[1]) == 1) then"); sb.append(" local stock = tonumber(redis.call('get', KEYS[1]));"); sb.append(" local num = tonumber(ARGV[1]);"); sb.append(" if (num <= 0) then"); sb.append(" return -4;"); sb.append(" end;"); sb.append(" if (stock <= 0) then"); sb.append(" return -1;"); sb.append(" end;"); sb.append(" if (stock >= num) then"); sb.append(" return redis.call('incrBy', KEYS[1], 0 - num);"); sb.append(" end;"); sb.append(" return -2;"); sb.append("end;"); sb.append("return -3;"); REDUCE_INVENTORY = sb.toString(); /** * @params 库存key * @return * -4:代表库存传进来的值是负数(非法值) * -3:库存未初始化 * 大于等于0:剩余库存(新增之后剩余的库存) */ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("if (redis.call('exists', KEYS[1]) == 1) then"); stringBuilder.append(" local num = tonumber(ARGV[1]);"); stringBuilder.append(" if (num < 0) then"); stringBuilder.append(" return -4;"); stringBuilder.append(" end;"); stringBuilder.append(" return redis.call('incrBy', KEYS[1], num);"); stringBuilder.append("end;"); stringBuilder.append("return -3;"); ADD_INVENTORY=stringBuilder.toString(); } }
}
以上代码都是针对单商品