Redisson 分布式锁的简单封装 使调用代码更简洁

2020-12-08 10:55:17 浏览数 (2)

1. 调用分布式锁的时候, 代码有点繁琐, 每次调用都要写这么一套, 如下

代码语言:javascript复制
RLock lock = redissonClient.getLock("lock-1");
try {
	boolean tryLock = lock.tryLock(1, 5, TimeUnit.SECONDS);
	if(tryLock) {
		System.out.println("******************** Business ********************");
	}
} catch (InterruptedException e) {
	e.printStackTrace();
} finally {
	if(lock.isHeldByCurrentThread()) {
		lock.unlock();
	}
}

2. 封装一个模板类 RedissonLockTemplate 用来调用锁, 封装一个回调类 TryLockCallback 用来包住执行的业务代码

代码语言:javascript复制
public interface TryLockCallback<T> {

	T doBusiness();
	
}
代码语言:javascript复制
public class RedissonLockTemplate {
	private Logger logger = LoggerFactory.getLogger(getClass()); 
	
	private RedissonClient redissonClient;

	public RedissonLockTemplate(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}
	
	public <T> T tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit, TryLockCallback<T> action) {
		RLock lock = redissonClient.getLock(lockKey);
		T result = null;
		try {
			boolean tryLock = lock.tryLock(waitTime, leaseTime, unit);
			if(tryLock) {
				result = action.doBusiness();
			}
		} catch (InterruptedException e) {
			logger.error("{} 锁发生中断异常!", lockKey, e);
		} finally {
			if(lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
		return result;
	}
}

3. 在 SpringBoot 项目中使用

代码语言:javascript复制
@SpringBootConfiguration
public class RedissonConfig {
	
	@Value("${spring.redis.host}")
	private String redisHost;
	@Value("${spring.redis.port}")
	private String redisPort;
	

	@Bean
	public RedissonClient redissonClient() {
		Config config = new Config();
//		config.useSingleServer().setAddress("redis://127.0.0.1:6379");
		config.useSingleServer().setAddress("redis://"   redisHost   ":"   redisPort);
		return Redisson.create(config);
	}
	
	@Bean
	public RedissonLockTemplate redissonLockTemplate() {
		RedissonLockTemplate redissonLockTemplate = new RedissonLockTemplate(redissonClient());
		return redissonLockTemplate;
	}
}
代码语言:javascript复制
@Autowired
private RedissonLockTemplate redissonLockTemplate;


@RequestMapping("/test")
@ResponseBody
public Integer test() {
	Integer result = redissonLockTemplate.tryLock("lock-1", 1, 5, TimeUnit.SECONDS, new TryLockCallback<Integer>() {
		@Override
		public Integer doBusiness() {
			// 业务代码写在这里
			System.out.println("************** doBusiness *************");
			return 0;
		}
	});
	return result;
}

大家看, 是不是简洁了很多.....

0 人点赞