LUA批量原子性操作redis

LUA执行redis指令

  • eval命令

LUA批量原子性操作redis_第1张图片

  • redisTemplate的execute方法:

LUA批量原子性操作redis_第2张图片

使用stringRedisTemplate执行LUA

注意:lua脚本的下标是从1开始的

//批量执行redis脚本拼接
StringBuffer script = new StringBuffer();
for (int i = 1; i <= redisKeyArr.length; i++) {
     script.append("redis.call('SET', KEYS[" + i + "], " + "'" + JSONObject.toJSONString(valueList.get(i - 1)) + "'" + ") ");
     script.append("redis.call('EXPIRE', KEYS["+ i +"], " + EquityConstant.SECONDS_OF_DAY + ") ");
}
DefaultRedisScript redisScript = new DefaultRedisScript();
redisScript.setScriptText(script.toString());
// 批量执行
stringRedisTemplate.execute(redisScript, keyList);

 使用JedisCluster执行LUA

/**
     * lua redis 脚本回滚
     * @param redisMap
     */
    public void redisLuaRollback(Map redisMap) {
        if (MapUtils.isEmpty(redisMap)) {
            return;
        }
        //从map中获取redis 中需要回滚的key
        List keyList = new ArrayList<>(redisMap.keySet());
        //list转数组为了传多个KEY
        String[] redisKeyArr = keyList.toArray(new String[keyList.size()]);
        //回滚脚本拼接
        StringBuffer script = new StringBuffer();
        script.append("local result = {} ");
        for (int i = 1; i <= redisKeyArr.length; i++) {
            script.append("result[" + i + "]=redis.call('DECRBY', KEYS[" + i + "], " + redisMap.get(redisKeyArr[i - 1]) + ") ");
        }
        script.append("return result");
        log.info("Lua脚本批量回滚key:{},结果={}", keyList, jedisCluster.eval(script.toString(), redisKeyArr.length, redisKeyArr));

    }

 

你可能感兴趣的:(redis)