Spring+Redis,Lua脚本大量缓存数据删除

        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 + "*");
    }

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值