1.引入pom
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1-jre</version>
</dependency>
<!-- 若使用redisson作为分布式锁底层,则需要引入 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
<version>2.2.4</version>
</dependency>
2.工具类
import com.baomidou.lock.DefaultLockKeyBuilder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Component;
/**
* 自定义分布式锁key生成规则
*
* @author: woniu
* @since: 2023/4/15 15:46
*/
@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {
public CustomKeyBuilder(BeanFactory beanFactory) {
super(beanFactory);
}
}
import com.baomidou.lock.LockFailureStrategy;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 自定义抢占锁失败执行策略
*
* @author: woniu
* @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("获取锁失败啦");
}
}
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;
/**
* redisson 重入锁
*
* @author woniu
*/
@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;
}
}
3.使用demo
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;
/**
* 分享一个分布式锁框架Lock4j
*/
@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");
}
}
4.配置文件
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