侧边栏壁纸
博主头像
EinTao博主等级

昨天再好,也走不回去;明天再难,也要抬脚继续。

  • 累计撰写 32 篇文章
  • 累计创建 3 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

SpringBoot 在启动的时候清理Redis锁

EinTao
2023-06-05 / 0 评论 / 0 点赞 / 43 阅读 / 236 字

前言

网络访问的时候需要对方法加锁,防止前端页面方法重复调用

String key = KeysHelper.createKVSKey(Configs.RepCatalog.ATOMIC_ACTION,
               Configs.AtomicAction.ACTION_DELIVERY_YG_MATCH, tid);
       try{
           return distributedLock.exe(key,30 * 60,() -> ygInvoiceMatchlock(tid));
       }catch (RuntimeException e){
           return toJsonResult(Result.apply("204", "该操作无法完成,已被锁定,请稍后操作"));
       }

存在问题

当系统重启或方法执行的时候锁没有释放,当系统启动的时候,该方法没法执行,虽然存在过期时间,但还是不太友好。

解决方法

在springBoot启动的时候,对这部分锁进行释放

import org.springframework.context.event.EventListener;

public class Starter {

   public static void main(String[] args) {
   	SpringApplication.run(Starter.class);
   }
   
   @EventListener
   public void onApplicationEvent(ApplicationReadyEvent event) {
   	RedisCommand redisCommand = SpringUtil.getBean(RedisCommand.class);
   	String keyParams = KeysHelper.createKVSKey(Configs.RepCatalog.ATOMIC_ACTION, "*");
   	Set<String> allKeys = redisCommand.keys(keyParams);

   	boolean blpre = ExceptionCatcherUtil.runWithCatch(() -> {
   		allKeys.forEach(k -> redisCommand.del(k));
   		return true;
   	});
   	GLog.info("删除Redis方法锁。");
   }
}
0

评论区