继上一篇 SpringBoot 整合 redis 踩坑日志以后,又学习了 redis 分布式锁,那为何须要分布式锁?java
在传统单体应用单机部署的状况下,可使用 Java 并发相关的锁,如 ReentrantLcok 或 synchronized 进行互斥控制。可是,随着业务发展的须要,原单体单机部署的系统,渐渐的被部署在多机器多JVM上同时提供服务,这使得原单机部署状况下的并发控制锁策略失效了,为了解决这个问题就须要一种跨JVM的互斥机制来控制共享资源的访问,这就是分布式锁要解决的问题。mysql
Redis 实现分布式锁不一样的人可能有不一样的实现逻辑,可是核心就是下面三个方法。web
1.SETNXSETNX key val 当且仅当 key 不存在时,set 一个 key 为 val 的字符串,返回1;若 key存在,则什么都不作,返回0。redis
2.Expireexpire key timeout 为 key 设置一个超时时间,单位为second,超过这个时间锁会自动释放,避免死锁。spring
3.Deletedelete key 删除 key 。sql
原理图以下:缓存
项目代码结构图安全
在 pom.xml 中添加 starter-web、starter-aop、starter-data-redis 的依赖bash
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
复制代码
在 application.properites 资源文件中添加 redis 相关的配置项服务器
server:
port: 1999
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis-plus-test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password: root
redis:
host: 127.0.0.1
port: 6379
timeout: 5000ms
password:
database: 0
jedis:
pool:
max-active: 50
max-wait: 3000ms
max-idle: 20
min-idle: 2
复制代码
一、建立一个 CacheLock 注解,属性配置以下
package com.tuhu.twosample.chen.distributed.annotation;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* 锁的注解
* @author chendesheng
* @create 2019/10/11 16:06
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheLock {
/**
* redis 锁key的前缀
*
* @return redis 锁key的前缀
*/
String prefix() default "";
/**
* 过时秒数,默认为5秒
*
* @return 轮询锁的时间
*/
int expire() default 5;
/**
* 超时时间单位
*
* @return 秒
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;
/**
* <p>Key的分隔符(默认 :)</p>
* <p>生成的Key:N:SO1008:500</p>
*
* @return String
*/
String delimiter() default ":";
}
复制代码
二、 key 的生成规则是本身定义的,若是经过表达式语法本身得去写解析规则仍是比较麻烦的,因此依旧是用注解的方式
package com.tuhu.twosample.chen.distributed.annotation;
import java.lang.annotation.*;
/**
* 锁的参数
* @author chendesheng
* @create 2019/10/11 16:08
*/
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheParam {
/**
* 字段名称
*
* @return String
*/
String name() default "";
}
复制代码
一、接口
package com.tuhu.twosample.chen.distributed.common;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* key生成器
* @author chendesheng
* @create 2019/10/11 16:09
*/
public interface CacheKeyGenerator {
/**
* 获取AOP参数,生成指定缓存Key
*
* @param pjp PJP
* @return 缓存KEY
*/
String getLockKey(ProceedingJoinPoint pjp);
}
复制代码
二、接口实现
package com.tuhu.twosample.chen.distributed.common;
import com.tuhu.twosample.chen.distributed.annotation.CacheLock;
import com.tuhu.twosample.chen.distributed.annotation.CacheParam;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* 经过接口注入的方式去写不一样的生成规则
* @author chendesheng
* @create 2019/10/11 16:09
*/
public class LockKeyGenerator implements CacheKeyGenerator {
@Override
public String getLockKey(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
CacheLock lockAnnotation = method.getAnnotation(CacheLock.class);
final Object[] args = pjp.getArgs();
final Parameter[] parameters = method.getParameters();
StringBuilder builder = new StringBuilder();
//默认解析方法里面带 CacheParam 注解的属性,若是没有尝试着解析实体对象中的
for (int i = 0; i < parameters.length; i++) {
final CacheParam annotation = parameters[i].getAnnotation(CacheParam.class);
if (annotation == null) {
continue;
}
builder.append(lockAnnotation.delimiter()).append(args[i]);
}
if (StringUtils.isEmpty(builder.toString())) {
final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
final Object object = args[i];
final Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
final CacheParam annotation = field.getAnnotation(CacheParam.class);
if (annotation == null) {
continue;
}
field.setAccessible(true);
builder.append(lockAnnotation.delimiter()).append(ReflectionUtils.getField(field, object));
}
}
}
return lockAnnotation.prefix() + builder.toString();
}
}
复制代码
熟悉 Redis 的朋友都知道它是线程安全的,咱们利用它的特性能够很轻松的实现一个分布式锁,如opsForValue().setIfAbsent(key,value)它的做用就是若是缓存中没有当前 Key 则进行缓存同时返回 true 反之亦然;当缓存后给 key 在设置个过时时间,防止由于系统崩溃而致使锁迟迟不释放造成死锁; 那么咱们是否是能够这样认为当返回 true 咱们认为它获取到锁了,在锁未释放的时候咱们进行异常的抛出….
package com.tuhu.twosample.chen.distributed.interceptor;
import com.tuhu.twosample.chen.distributed.annotation.CacheLock;
import com.tuhu.twosample.chen.distributed.common.CacheKeyGenerator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
/**
* @author chendesheng
* @create 2019/10/11 16:11
*/
@Aspect
@Configuration
public class LockMethodInterceptor {
@Autowired
public LockMethodInterceptor(StringRedisTemplate lockRedisTemplate, CacheKeyGenerator cacheKeyGenerator) {
this.lockRedisTemplate = lockRedisTemplate;
this.cacheKeyGenerator = cacheKeyGenerator;
}
private final StringRedisTemplate lockRedisTemplate;
private final CacheKeyGenerator cacheKeyGenerator;
@Around("execution(public * *(..)) && @annotation(com.tuhu.twosample.chen.distributed.annotation.CacheLock)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
CacheLock lock = method.getAnnotation(CacheLock.class);
if (StringUtils.isEmpty(lock.prefix())) {
throw new RuntimeException("lock key can't be null...");
}
final String lockKey = cacheKeyGenerator.getLockKey(pjp);
try {
//key不存在才能设置成功
final Boolean success = lockRedisTemplate.opsForValue().setIfAbsent(lockKey, "");
if (success) {
lockRedisTemplate.expire(lockKey, lock.expire(), lock.timeUnit());
} else {
//按理来讲 咱们应该抛出一个自定义的 CacheLockException 异常;
throw new RuntimeException("请勿重复请求");
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("系统异常");
}
} finally {
//若是演示的话须要注释该代码;实际应该放开
// lockRedisTemplate.delete(lockKey);
}
}
}
复制代码
在接口方法上添加 @CacheLock(prefix = "test"),而后动态的值能够加上@CacheParam;生成后的新 key 将被缓存起来;(如:该接口 token = 1,那么最终的 key 值为 test:1,若是多个条件则依次类推)
package com.tuhu.twosample.chen.controller;
import com.tuhu.twosample.chen.distributed.annotation.CacheLock;
import com.tuhu.twosample.chen.distributed.annotation.CacheParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author chendesheng
* @create 2019/10/11 16:13
*/
@RestController
@RequestMapping("/chen/lock")
@Slf4j
public class LockController {
@CacheLock(prefix = "test")
@GetMapping("/test")
public String query(@CacheParam(name = "token") @RequestParam String token) {
return "success - " + token;
}
}
复制代码
须要注入前面定义好的 CacheKeyGenerator 接口具体实现 ….
package com.tuhu.twosample;
import com.tuhu.twosample.chen.distributed.common.CacheKeyGenerator;
import com.tuhu.twosample.chen.distributed.common.LockKeyGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* @author chendesheng
* @since 2019-08-06
*/
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
@MapperScan("com.tuhu.twosample.chen.mapper")
public class TwoSampleApplication {
public static void main(String[] args) {
SpringApplication.run(TwoSampleApplication.class, args);
}
@Bean
public CacheKeyGenerator cacheKeyGenerator() {
return new LockKeyGenerator();
}
}
复制代码
启动项目,在postman中输入url:<http://localhost:1999/chen/lock/test?token=1 >
第一次请求结果:
第二次请求结果:
等key过时了请求又恢复正常。
可是这种分布式锁也存在着缺陷,若是A在setnx成功后,A成功获取锁了,也就是锁已经存到 Redis 里面了,此时服务器异常关闭或是重启,将不会执行咱们的业务逻辑,也就不会设置锁的有效期,这样的话锁就不会释放了,就会产生死锁。 因此还须要对锁进行优化,好好学习学习,嘎嘎嘎嘎。