码迷,mamicode.com
首页 > 其他好文 > 详细

【分布式Redis锁】【并发编程】Redis分布式锁实例

时间:2018-07-11 19:39:42      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:线程等待   class   并发编程   string   service   interrupt   setnx   分布式锁   业务   

在处理业务代码时,总会遇到多线程对同一资源竞争,此时对已经抢到资源的线程做Lock。

这里暂时先不考虑 是否是公平锁,是否可以重入的情况。

 

给出实现代码,key为加锁的维度。

@Service
public class LockManagementService {
    private static Logger logger = LoggerFactory.getLogger(LockManagementService.class);
    
    @Autowired
    private RedisService redisService;
    
    /**
     * 加分布式锁
     */
    public void getLock(String type,String value){
        String key = type+value;
        Long result = redisService.setnx(key, "00");
        logger.info("{},开始创建分布式锁...",key);
        while(result==0L){
            Long ttl  =redisService.getTtl(key);
            logger.info("{},并发等待中...,剩余过期时间:{} s",key,ttl);
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                logger.error("分布式锁线程等待出现异常:"+ e.getMessage(),e);
            };
            result = redisService.setnx(key, "00");
        }
        logger.info("{},成功创建分布式锁...",key);
        redisService.setKeyExpire(key, 300);//单位秒
    }
    /**
     * 释放分布式锁
     */
    public void unLock(String type,String value){
        String key = type+value;
        redisService.del(key);
        logger.info("{},成功释放分布式锁...",key);
    }
    
}

 

【分布式Redis锁】【并发编程】Redis分布式锁实例

标签:线程等待   class   并发编程   string   service   interrupt   setnx   分布式锁   业务   

原文地址:https://www.cnblogs.com/liuxs13/p/9295940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!