本文基于ThreadLocal原理,实现了一个上下文状态管理组件Scope,通过开启一个自定义的Scope,在Scope范围内,可以通过Scope各个方法读写数据;
通过自定义线程池实现上下文状态数据的线程间传递;
提出了一种基于Filter和Scope的Request粒度的上下文管理方案
1. maven依赖
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 若使用redisson作为分布式锁底层,则需要引入 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2. 基于Spring AOP的声明式和编程式分布式锁,支持RedisTemplate、Redisson、Zookeeper
package com.example.demo.controller;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.annotation.Lock4j;
import com.example.demo.executor.RedissonLockNewExecutor;
import org.springframework.beans.factory.annotation.Autowired;
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("/mock")
public class MockController {
@GetMapping("/lockMethod")
@Lock4j(keys = {"#key"}, acquireTimeout = 10, expire = 10000
,executor = RedissonLockNewExecutor.class
)
public String lockMethod(@RequestParam String key) throws InterruptedException {
Thread.sleep(10000);
return key;
}
@Autowired
private LockTemplate lockTemplate;
@GetMapping("/lockMethodCostom")
public String lockMethodCostom(@RequestParam String key) {
LockInfo lock = lockTemplate.lock(key, 10000L, 2000L, RedissonLockNewExecutor.class);
if (lock == null) {
// 获取不到锁
throw new RuntimeException("业务处理中,请稍后再试...");
}
// 获取锁成功,处理业务
try {
doBusiness();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lockTemplate.releaseLock(lock);
}
return key;
}
private void doBusiness() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("woniuhaobang");
}
}
3. 自定义分布式锁key生成规则
package com.example.demo.executor;
import com.baomidou.lock.DefaultLockKeyBuilder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Component;
/**
*
*
* @author: panlei
* @since: 2023/4/15 15:46
*/
@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {
public CustomKeyBuilder(BeanFactory beanFactory) {
super(beanFactory);
}
}
自定义抢占锁失败执行策略
package com.example.demo.executor;
import com.baomidou.lock.LockFailureStrategy;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 自定义抢占锁失败执行策略
*
* @author: panlei
* @since: 2023/4/15 15:49
*/
@Component
public class GrabLockFailureStrategy implements LockFailureStrategy {
@Override
public void onLockFailure(String key, Method method, Object[] arguments) {
throw new RuntimeException("获取锁失败啦");
}
}
4. redisson 重入锁
/*
* Copyright (c) 2018-2022, baomidou (63976799@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.demo.executor;
import com.baomidou.lock.executor.AbstractLockExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Slf4j
@RequiredArgsConstructor
public class RedissonLockNewExecutor extends AbstractLockExecutor<RLock> {
private final RedissonClient redissonClient;
@Override
public boolean renewal() {
return true;
}
@Override
public RLock acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
try {
final RLock lockInstance = redissonClient.getLock(lockKey);
final boolean locked = lockInstance.tryLock(acquireTimeout, expire, TimeUnit.MILLISECONDS);
return obtainLockInstance(locked, lockInstance);
} catch (InterruptedException e) {
return null;
}
}
@Override
public boolean releaseLock(String key, String value, RLock lockInstance) {
if (lockInstance.isHeldByCurrentThread()) {
try {
return lockInstance.forceUnlockAsync().get();
} catch (ExecutionException | InterruptedException e) {
return false;
}
}
return false;
}
}
5. 配置文件
spring:
redis:
database: 0
# Redis服务器地址 写你的ip
host: 192.168.56.10
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password: 123456
# 连接池最大连接数(使用负值表示没有限制 类似于mysql的连接池
jedis:
pool:
max-active: 200
# 连接池最大阻塞等待时间(使用负值表示没有限制) 表示连接池的链接拿完了 现在去申请需要等待的时间
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 10
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒) 去链接redis服务端
timeout: 6000