Spring Boot (33) 分布式锁
上一篇中使用的Guava Cache,如果在集群中就不可以用了,需要借助Redis、Zookeeper之类的中间件实现分布式锁。
导入依赖
在pom.xml中需要添加的依赖包:stater-web、starter-aop、starter-data-redis
<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>
属性配置
spring:
redis:
host: 10.211.55.5 #redis服务器地址
timeout: 10000 #超时时间
database: 0 #0-15 16个库 默认0
lettuce:
pool:
max-active: 8 #最大连接数
max-wait: -1 #默认-1 最大连接阻塞等待时间
max-idle: 8 #最大空闲连接 默认8
min-idle: 0 #最小空闲连接
CacheLock注解
package com.spring.boot.annotation; import java.lang.annotation.*;
import java.util.concurrent.TimeUnit; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheLock {
/**
* redis 锁的前缀
* @return
*/
String prefix() default ""; /**
* 过期时间
* @return
*/
int expire() default 5; /**
* 超时时间单位
* @return
*/
TimeUnit timeUnit() default TimeUnit.SECONDS; /**
* 可以的分隔符(默认:)
* @return
*/
String delimiter() default ":";
}
CacheParam注解
package com.spring.boot.annotation; import java.lang.annotation.*; @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface CacheParam {
/**
* 字段名称
*
* @return String
*/
String name() default "";
}
Key生成策略(接口)
package com.spring.boot.annotation; import org.aspectj.lang.ProceedingJoinPoint; public interface CacheKeyGenerator { String getLockKey(ProceedingJoinPoint pjp);
}
Key生成策略(实现)
主要是解析带CacheLock注解的属性,获取对应的属性值,生成一个全新的缓存Key
package com.spring.boot.annotation; import io.lettuce.core.dynamic.support.ReflectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature; import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter; 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();
// TODO 默认解析方法里面带 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 (builder == null || 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();
}
}
Lock拦截器(AOP)
opsForValue().setIfAbsent(key,value)如果缓存中没有当前key则进行缓存,同时返回true,否则 返回false。当缓存后给key在设置个过期时间,防止因为系统崩溃而导致锁迟迟不释放形成死锁。 我们就可以这样人物当返回true它获取到锁了,在所未释放的时候我们进行异常的抛出
package com.spring.boot.annotation; import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.util.StringUtils; import java.lang.reflect.Method; @Aspect
@Configuration
public class LockMethodInterceptor { private final StringRedisTemplate lockRedisTemplate;
private final CacheKeyGenerator cacheKeyGenerator; @Autowired
public LockMethodInterceptor(StringRedisTemplate lockRedisTemplate, CacheKeyGenerator cacheKeyGenerator) {
this.lockRedisTemplate = lockRedisTemplate;
this.cacheKeyGenerator = cacheKeyGenerator;
} @Around("execution(public * *(..)) && @annotation(com.spring.boot.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 don't null...");
}
final String lockKey = cacheKeyGenerator.getLockKey(pjp);
try {
// 采用原生 API 来实现分布式锁
final Boolean success = lockRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), new byte[0], Expiration.from(lock.expire(), lock.timeUnit()), RedisStringCommands.SetOption.SET_IF_ABSENT));
if (!success) {
// TODO 按理来说 我们应该抛出一个自定义的 CacheLockException 异常;
throw new RuntimeException("请勿重复请求");
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("系统异常");
}
} finally {
// TODO 如果演示的话需要注释该代码;实际应该放开
// lockRedisTemplate.delete(lockKey);
}
}
}
控制器
package com.spring.boot.controller; import com.spring.boot.annotation.CacheLock;
import com.spring.boot.annotation.CacheParam;
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; @RestController
@RequestMapping("/books")
public class BookController { @CacheLock(prefix = "books")
@GetMapping
public String query(@CacheParam(name = "token") @RequestParam String token){
return "success - " + token;
}
}
还要在启动类中注入CacheKeyGenerator接口具体实现
@SpringBootApplication
public class BootApplication{ public static void main(String[] args) {
SpringApplication.run(BootApplication.class,args);
} @Bean
public CacheKeyGenerator cacheKeyGenerator() {
return new LockKeyGenerator();
}
测试:
http://localhost:8088/books?token=1
5秒内再次请求
Spring Boot (33) 分布式锁的更多相关文章
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
- spring boot redis分布式锁 (转)
一. Redis 分布式锁的实现以及存在的问题 锁是针对某个资源,保证其访问的互斥性,在实际使用当中,这个资源一般是一个字符串.使用 Redis 实现锁,主要是将资源放到 Redis 当中,利用其原子 ...
- Spring Integration实现分布式锁
学习本篇之前,可以先看下文章 什么是分布式锁,了解下基本概念. 之前都是手写一个分布式锁,其实Spring早就提供了分布式锁的实现.早期,分布式锁的相关代码存在于Spring Cloud的子项目Spr ...
- Spring Boot Quartz 分布式集群任务调度实现
Spring Boot Quartz 主要内容 Spring Scheduler 框架 Quartz 框架,功能强大,配置灵活 Quartz 集群 mysql 持久化定时任务脚本(tables_mys ...
- 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)
本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...
- Spring Boot与分布式
---恢复内容开始--- 分布式.Dubbo/Zookeeper.Spring Boot/Cloud 一.分布式应用 在分布式系统中,国内常用zookeeper+dubbo组合, 而Spring Bo ...
- Java 架构师+高并发+性能优化+Spring boot大型分布式项目实战
视频课程内容包含: 高级 Java 架构师包含:Spring boot.Spring cloud.Dubbo.Redis.ActiveMQ.Nginx.Mycat.Spring.MongoDB.Zer ...
- 分布式缓存技术redis系列(五)——redis实战(redis与spring整合,分布式锁实现)
本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...
- 从0开始用spring boot编写分布式配置中心-peppa
欢迎大家一起来编写peppa github地址: github 交流群: 目前市面上比较流行的分布式配置中心有disconf.apollo,用起来还是比较方便的,然而由于在权限管理这块做得不够好,导致 ...
随机推荐
- easyUi 学习笔记 (二 ) 使用tabs 里datagridview 发送ajax请求 不访问后台的问题
这个BUG 我花了一个半小时, 还是看不出哪里的问题, 于是就百度到这么一段话,我需要记住 <================================================= ...
- ubuntu语言设置成汉语
打开设置system setting,进入语言支持,有语言和地区格式.下载须要的语言并应用到整个系统. 按说明来就可以 这样的方法使得部分英语变为汉语.
- Java解惑四:异常之谜
谜题36 finally语句中的return语句会覆盖掉try语句中的. 谜题37 该部分还须要进一步理解 一个方法能够抛出的被检查异常集合是它所适用的全部类型声明要抛出的被检查集合的交集.
- Python正則表達式小结(1)
学习一段python正則表達式了, 对match.search.findall.finditer等函数作一小结 以下以一段网页为例,用python正則表達式作一个范例: strHtml = '''& ...
- 另类创业招聘(REV#2)
项目一 项目名:苏格拉底网 项目性质:人才測评为主.辅助以简易人才招聘功能的小众功能站点.项目使用了自主研发的人才測评算法以及人格分类模型(与MBTI非常相似). 项目相关网址:sugeladi.ne ...
- Java小白手记:WEB项目等
机缘巧合之下,工作中得以用一下java.我向来对java很感兴趣,想从.NET转到java久矣,机会难得,久旱逢甘霖. 这次主要是跟web项目有关.在此之前,我了解到JAVA分为三大块:j2se.j2 ...
- asp.net mvc 的 视图(view )的模块化开发
目前所在项目有一个视图,几个模块都涉及到,对应不同的开发人员,虽然有SVN在管理,但代码冲突时有发生.并且大家的代码挤于其中,逻辑比较容易混乱. 将不同部件独立出去,实有必要. 分离方式,我知道的有 ...
- 如何在Mac OS X 中运行Lua (Running Lua on Mac OS X)
参考文章:1) http://www.oschina.net/question/12_769552) http://rudamoura.com/luaonmacosx.html 最近在为iOS开发游戏 ...
- POJ1743 Musical Theme 最长重复子串 利用后缀数组
POJ1743 题目意思是求不重叠的最长相同变化的子串,输出该长度 比如1 2 3 4 5 6 7 8 9 10,最长长度为5,因为子串1 2 3 4 5 和 6 7 8 9 10变化都一样的 思路: ...
- 4-2 买家类目-dao(下)
查询出来的对象ProductCategory就已经有updateTime和createTime了,然而你只是把对象的categoryType给修改了一下,修改之后就执行save方法保存了.所以它还是原 ...