关注我,升职加薪就是你!
Jedis锁的用处就不多说了,直接上代码。
开始写代码之前,我们需要先引入lombok和redis。
<!-- 引用lombok以输出日志. -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
1、创建一个工厂类SpringFactory,提供静态获取Spring bean 的工厂方法。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author: Max
* @time: 2022/6/29
* @description: 提供静态获取Spring bean 的工厂方法
*/
@Component
public class SpringFactory implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringFactory() {
}
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return applicationContext.getBean(beanClass);
}
public static <T> T getBean(String beanName, Class<T> beanClass) {
return applicationContext.getBean(beanName, beanClass);
}
public static <T> T getBean(String beanName) {
return (T)applicationContext.getBean(beanName);
}
}
2、接下来是我们的主角,Jedis锁机制类JedisLock
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @author: Max
* @time: 2022/6/29
* @description: Jedis 锁机制的实现
*/
@Slf4j
public class JedisLock {
/** 虚拟key的后缀 */
private static final String PREFIX = "_lock";
/** 加锁标志 */
public static final String LOCKED = "TRUE";
/** 毫秒与毫微秒的换算单位 1毫秒 = 1000000毫微秒 */
public static final long MILLI_NANO_CONVERSION = 1000 * 1000L;
/** 默认超时时间(毫秒) */
public static final long DEFAULT_TIME_OUT = 1000;
public static final Random RANDOM = new Random();
/** 锁的超时时间(秒),过期删除 */
public static final int EXPIRE = 20 ;
private StringRedisTemplate redisTemplate;
/** 虚拟key,用于实现锁的key ,组合值:key_lock */
private String key = "";
/** 锁状态标志 */
private boolean locked = false;
/**
* @Author:Max
* @Description:构造函数:创建JedisLock对象
* @Date:2022/6/29
* @Param:[key] key 需要加锁的key
* @Return:
*/
public JedisLock(String key) {
this.key = key + PREFIX;
this.redisTemplate = SpringFactory.getBean(StringRedisTemplate.class);
}
/**
* @Author:Max
* @Description:对指定的key进行加锁 说明:应该以: try { if(lock()){doSomething(); }} finally { unlock(); }
* @Date:2022/6/29
* @Param:[]
* @Return:boolean 返回加锁的状态:true 成功 | false 失败
*/
public boolean lock() {
return lock(DEFAULT_TIME_OUT);
}
/**
* @Author:Max
* @Description:对指定的key进行加锁 说明:应该以: try { if(lock()){doSomething(); }} finally { unlock(); }
* @Date:2022/6/29
* @Param:[timeout] 设置超时时间
* @Return:boolean 返回加锁的状态:true 成功 | false 失败
*/
public boolean lock(long timeout) {
return lock(timeout,EXPIRE);
}
/**
* @Author:Max
* @Description:对指定的key进行加锁 说明:应该以: try { if(lock()){doSomething(); }} finally { unlock(); }
* @Date:2022/6/29
* @Param:[timeout, expire] 设置超时时间
* timeout 获取锁的超时时间
* expire 锁的超时时间(秒),过期删除
* @Return:boolean 返回加锁的状态:true 成功 | false 失败
*/
public boolean lock(long timeout, int expire) {
long nano = System.nanoTime();
timeout *= MILLI_NANO_CONVERSION;
try {
while ((System.nanoTime() - nano) < timeout) {
if (this.redisTemplate.opsForValue().setIfAbsent(this.key, LOCKED)) {
this.redisTemplate.expire(this.key, expire,TimeUnit.SECONDS);
this.locked = true;
log.debug("Redis Locked加锁过程,对"+this.key+"成功加锁!!");
return this.locked;
}
// 短暂休眠,避免出现活锁
Thread.sleep(20, RANDOM.nextInt(500));
}
} catch (Exception e) {
throw new RuntimeException("Jedis 在加锁过程中key:" + this.key+ "进行加锁失败!!!", e);
}
return false;
}
/**
* @Author:Max
* @Description:解锁 无论是否加锁成功,都需要调用unlock try { if(lock()){doSomething(); }} finally { unlock(); }
* @Date:2022/6/29
* @Param:[]
* @Return:void
*/
public void unlock() {
synchronized (this) {
try {
if (this.locked && this.isExsits()) {
this.redisTemplate.delete(this.key);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @Author:Max
* @Description:判断当前键是否被锁
* @Date:2022/6/29
* @Param:[]
* @Return:boolean
*/
public synchronized boolean isExsits(){
try {
return this.redisTemplate.hasKey(key);
} catch (Exception e) {
log.error("Jedis Lock 判断当前key:"+this.key+"是否获取锁失败!!",e);
}
return false;
}
}
3、测试一下。
3.1 创建一个异常处理类BusinessException。
import java.text.MessageFormat;
/**
* @author: Max
* @time: 2022/6/29
* @description: 业务异常基类。所有自定义异常统一继承该类。
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String code = "11";
private String message;
public BusinessException(String message) {
super(message);
this.message = message;
}
public BusinessException(String errorCode,String message ) {
super(message);
this.code = errorCode;
this.message = message;
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
this.message = message;
}
public BusinessException(String errorCode,String message, Throwable cause) {
super(message, cause);
this.code = errorCode;
this.message = message;
}
/**
* @Author:Max
* @Description:支持动态参数。如this is a message,{0},{1}
* @Date:2022/6/29
* @Param:[errorCode, message, values]
* @Return:
*/
public BusinessException(String errorCode,String message,Object ... values) {
this(errorCode, MessageFormat.format(message,values));
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3.2 实测。
import com.example.demo.common.exception.BusinessException;
import com.example.demo.testorg.dto.UserDto;
import com.example.demo.testorg.service.ITestService;
import com.example.demo.web.helper.JedisLock;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author: Max
* @time: 2022/6/21
* @description: 测试控制层
*/
@RestController
@RequestMapping("/api/test")
public class TestController {
@Resource
private ITestService iTestService;
@RequestMapping(value = "update", method = RequestMethod.POST)
public void update(@RequestBody UserDto userReq){
JedisLock jLock = new JedisLock("update");
// 加锁处理
try {
if (jLock.lock(1)) {
this.iTestService.update(userReq);
}else{
throw new BusinessException("正在更新,请稍后!!!");
}
}finally {
jLock.unlock();
}
}
}
如果1s内重复请求该接口,则会抛出如下提示语。
正在更新,请稍后!!!
好了,完事。
关注我,升职加薪就是你!