1、Lua脚本:redis.lua
(1)删除所有数据,循环遍历删除,每次删除1w条。直到数据删除完毕为止
local cursor = 0
local keyNum = 0
repeat
local res = redis.call('SCAN',cursor,'MATCH',KEYS[1],'COUNT', 10000)
if(res ~= nil and #res>=0)
then
cursor = tonumber(res[1])
local ks = res[2]
if(ks ~= nil and #ks>0)
then
for i=1,#ks,1 do
local key = tostring(ks[i])
redis.call('UNLINK',key)
end
keyNum = keyNum + #ks
end
end
until( cursor <= 0 )
return keyNum
(2)批量数据删除,循环遍历 40次,每次删除1w条数据
local cursor = 0
local keyNum = 0
local a = 0
while(a < 40)
do
local res = redis.call('SCAN',cursor,'MATCH',KEYS[1],'COUNT', 10000)
if(res ~= nil and #res>=0)
then
cursor = tonumber(res[1])
if (cursor <= 0) then
break
end
local ks = res[2]
if(ks ~= nil and #ks>0)
then
for i=1,#ks,1 do
local key = tostring(ks[i])
redis.call('UNLINK',key)
end
keyNum = keyNum + #ks
end
end
a = a + 1
end
return keyNum
2、lua文件存放在resources目录下,工具类调用脚本
@Slf4j
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void runLuaDel(String key) {
try {
List<String> keyList = new ArrayList<>();
keyList.add(key);
//调用lua脚本并执行
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//返回类型是Long
redisScript.setResultType(Long.class);
//lua文件存放在resources目录下
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis.lua")));
Long res = redisTemplate.execute(redisScript, keyList);
log.error("删除成功数量:" + res);
}catch (Exception e){
log.error("[lua脚本]删除异常", e);
}
}
}
3、调用
@Scheduled(cron = "0 0 0 * * ?")
public void redisRemove() {
log.error("清除redis昨日数据");
String yesterday = DateUtil.getYesterday("yyyyMMdd");
redisUtil.runLuaDel(yesterday + "*");
}