直接上代码 CV 即用,调试了一下午,好用就点个赞
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class RedisUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private static String CHECK_EXIST_TEMPLATE = "if redis.call('exists', KEYS[%s]) == 1 then return 0 end; \r\n";
private static String SET_TEMPLATE = "redis.call('set', KEYS[%s], ARGV[%s]); \r\n";
private static String EXPIRE_TEMPLATE = "redis.call('expire', KEYS[%s], %s); \r\n";
private static String EXPIRE_SEPARATE_TEMPLATE = "redis.call('expire', KEYS[%s], ARGV[%s]); \r\n";
private static String DELETE_TEMPLATE = "redis.call('del', KEYS[%s]); \r\n";
private static String RETURN_TEMPLATE = "return 1; \r\n";
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
this.applicationContext = ac;
}
public static Boolean luaSetBatch(Map<String, ?> kvs, Long secondTime) {
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
StringBuilder scriptStr = new StringBuilder("");
LuaParam luaParam = new LuaParam();
kvs.forEach((k, v) -> {
scriptStr.append(String.format(CHECK_EXIST_TEMPLATE, luaParam.getIndex()));
luaParam.setIndex(luaParam.getIndex() + 1);
luaParam.getKeys().add(k);
luaParam.getValues().add(v);
});
luaParam.setIndex(1);
kvs.forEach((k, v) -> {
scriptStr.append(String.format(SET_TEMPLATE, luaParam.getIndex(), luaParam.getIndex()));
luaParam.setIndex(luaParam.getIndex() + 1);
});
luaParam.setIndex(1);
if (secondTime != null) {
kvs.forEach((k, v) -> {
scriptStr.append(String.format(EXPIRE_TEMPLATE, luaParam.getIndex(), secondTime));
luaParam.setIndex(luaParam.getIndex() + 1);
});
}
scriptStr.append(RETURN_TEMPLATE);
RedisScript script = RedisScript.of(scriptStr.toString(), Object.class);
Long execute = (Long) redisTemplate.execute(script, luaParam.getKeys(), luaParam.getValues().toArray());
return execute >= 1;
}
public static void luaDelBatch(Collection<String> keys) {
StringBuilder scriptStr = new StringBuilder();
LuaParam luaParam = new LuaParam();
for (String key : keys) {
scriptStr.append(String.format(DELETE_TEMPLATE, luaParam.getIndex()));
luaParam.setIndex(luaParam.getIndex() + 1);
luaParam.getKeys().add(key);
}
RedisScript script = RedisScript.of(scriptStr.toString(), Object.class);
redisTemplate().execute(script, luaParam.getKeys());
}
@Data
static class LuaParam {
private int index = 1;
private List<String> keys = new ArrayList<>();
private List values = new ArrayList<>();
private List<Long> expireTimes = Lists.newArrayList();
}