Redisson 分佈式鎖的簡單封裝 使調用代碼更簡潔

1. 調用分佈式鎖的時候, 代碼有點繁瑣, 每次調用都要寫這麼一套, 如下

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 用來包住執行的業務代碼

public interface TryLockCallback<T> {

	T doBusiness();
	
}
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 項目中使用

@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;
	}
}
@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;
}

大家看, 是不是簡潔了很多.....

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章