利用Redisson实现分布式锁,并防止重复提交

关于Redisson的基础概念,参照Redisson基础

要想实现此功能需要以下几步:

1.依赖包

这里用的是jdk8+的版本

 <dependency>
      <groupId>org.redisson</groupId>
      <artifactId>redisson</artifactId>
      <version>3.3.2</version>
    </dependency>

2.Spring整合

注意设置schema文件

 <redisson:client id="redissonClient2">
     
        <redisson:single-server address="192.168.238.129:6379"/>
    </redisson:client>

3.工具类

默认锁

@Component
public class DistributedRedisLock implements InitializingBean {
	private static final Logger _log = Logger.getLogger(DistributedRedisLock.class);
	@Autowired
	private RedissonClient redissonClient;
	public static Redisson redisson;
	
	/**
	 * 获取默认锁
	 */
	public static RLock acquireLock(String lockName) {
		RLock fairLock = redisson.getLock(lockName);
		fairLock.lock();// 手动去解锁
		_log.info("锁 - " + lockName + "获取成功"); return fairLock;
	}
	
	/**
	 * 释放默认锁
	 */
	public static void realeaseLock(RLock fairLock) {
		fairLock.unlock();	
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		redisson = (Redisson) redissonClient;
		_log.info(redisson.getConfig().toJSON());
	}
}

如何防止重复呢?


/**
	 * 存入分布式set对象中
	 * @param name
	 * @param value
	 * @return
	 */
	public RSet<String> setSet(String name, String value){
		RSet<String> set = redisson.getSet(name);
		set.add(value);
		return  set;
	}

	/**
	 * 检查分布式对象是否存在
	 * @param name
	 * @return
	 */
	public Boolean existSet(String name){
		RSet<String> set = redisson.getSet(name);
		if (!set.isEmpty()) {
			return  true;
		}
		return  false;
	}

调用代码:

	String lockname="lockname";
		
	RLock fairLock=DistributedRedisLock.acquireLock(lockname);
 try {//不存在设置到redis
if (!DistributedRedisLock.existSet(lockname)) {
DistributedRedisLock.setSet(lockname, "1111");
//业务逻辑begin
} else {
//redis中有则不处理业务逻辑
}
}finally {
DistributedRedisLock.realeaseLock(fairLock);
}

    原文作者:java锁
    原文地址: https://blog.csdn.net/u014042066/article/details/72830939
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞