zoukankan      html  css  js  c++  java
  • 一种简单的redis分布式锁方案

    前言

    用于分布式程序彼此之间不能同时执行的场景。例如计算程序等。

    代码

    锁工具类

    
    @Component
    public class RedisLockUtil {
    
    	@Autowired
    	private RedisTemplate redisTemplate;
    
    	private static final String CALC_LOCK_KEY = "CalculateLock";
    	private static final Long CALC_LOCK_TIME = 30L;
    
    
    	public boolean setIfAbsent (String key,String value,Long lockTime) {
    		return redisTemplate.opsForValue().setIfAbsent(key,value,lockTime,TimeUnit.MINUTES);
    	}
    
    	public String getValue(String key) {
    		return (String) redisTemplate.opsForValue().get(key);
    	}
    
    	public void delete (String key) {
    		redisTemplate.delete(key);
    	}
    
    	public boolean calcLock (String value) {
    		return redisTemplate.opsForValue().setIfAbsent(CALC_LOCK_KEY,value,CALC_LOCK_TIME,TimeUnit.MINUTES);
    	}
    
    	public String getCalcValue () {
    		return (String) redisTemplate.opsForValue().get(CALC_LOCK_KEY);
    	}
    
    	public String getTimeSeed(){
    		return String.valueOf(new Date().getTime());
    	}
    
    	public void unCalclock () {
    		redisTemplate.delete(CALC_LOCK_KEY);
    	}
    
    
    }
    
    

    实际调用的代码

    @PostMapping("/calc")
    public void calc() throws Exception{
    
    	String redisValue = "计算"+redisLockUtil.getTimeSeed();
    	boolean flag = redisLockUtil.calcLock(redisValue);
    	if(!flag){
    		return ;
    	}
    	try{
    		//业务代码
    	}catch (Exception e){
    		e.printStackTrace();
    		//业务代码
    		return ;
    	}finally {
    		//为了防止过期导致删除了其他人的锁
    		if(redisValue.equals(redisLockUtil.getCalcValue())){
    			redisLockUtil.unCalclock();
    		}
    	}
    	return;
    }
    
  • 相关阅读:
    Go 好用第三方库
    Go 的beego 框架
    Go 的gin 框架 和 gorm 和 html/template库
    Go 常用的方法
    Dijkstra 的两种算法
    邻接矩阵
    next permutation 的实现
    最优二叉树 (哈夫曼树) 的构建及编码
    思维题— Count the Sheep
    STL— bitset
  • 原文地址:https://www.cnblogs.com/jichi/p/13537094.html
Copyright © 2011-2022 走看看