package com.itq.branck.util.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @author :qidong_wei
* @date :Created in 2021/3/1 10:12
* 文件说明:</p>
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisLockTest {
@Autowired
private RedisTemplate redisTemplate;
/**
* @param value 模拟分布式锁
* 1、加锁后如果因为停电等原因,造成锁不释放,变为死锁,那么给锁设置过期时间
* 2、如果加锁后过期时间内未处理完业务逻辑,那么该条业务应该终止,数据不写回redis
* 3、业务代码执行超时,需要给执行业务逻辑增加超时时间监控,超时执行不会写 redis 数据
* 4、设定合理的超时时间范围
*/
public String getRedis(int value) {
String uuid = UUID.randomUUID().toString();
Boolean result = redisTemplate.opsForValue().setIfAbsent("jike", uuid, 1, TimeUnit.SECONDS);
// 如果set值失败,加锁,反之继续执行业务流程
// 加过期时间防止在设置了锁之后出现异常,导致死锁不进行释放
if (!result) {
return "系统繁忙";
}
String items = (String) redisTemplate.opsForValue().get("items");
int item = Integer.valueOf(items);
try {
item = item - value;
System.out.println("方法执行结束");
redisTemplate.opsForValue().set("items", String.valueOf(item));
} catch (Exception e) {
System.out.println("系统繁忙");
return "系统繁忙";
} finally {
if (uuid.equals(redisTemplate.opsForValue().get("jike"))) {
// 订单处理完成释放锁资源
redisTemplate.delete("jike");
}
}
return "success";
}
@Test
public void test() {
RedisLockTest s = new RedisLockTest();
s.getRedis(12);
}
}
redis 演示分布式锁
最新推荐文章于 2024-03-03 21:44:00 发布