一、分布式锁介绍
Spring Boot 实现 Redis 分布式锁在 spring-integration 这个项目中,参考:
https://docs.spring.io/spring-integration/docs/5.3.1.RELEASE/reference/html/redis.html#redis-lock-registry
首先来看下 LockRegistry 锁注册接口的所有实现类结构图:

二、分布式锁实战
1. pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1. 注解层
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedLock {
String value() default "";
int time() default 30;
}
2. 切面层
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
/**
* @Description 分布式锁切面,使用“RedisLockRegistry”实现分布式锁
* @Author jzhao
* @Date 2021-3-6 10:32
**/
@Component
@Aspect
public class DistributedLockAop {
private static Logger logger = LoggerFactory.getLogger(DistributedLockAop.class);
private WebApplicationContext webApplicationContext;
public DistributedLockAop(WebApplicationContext webApplicationContext) {
this.webApplicationContext = webApplicationContext;
}
@Pointcut("@annotation(com.online.taxi.order.annotation.DistributedLock)")
private void apiAop() {
//此处为切点,不需要实现方法
}
@Around("apiAop()")
public Object aroundApi(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
Object[] args = point.getArgs();
DistributedLock distributedLock = method.getAnnotation(DistributedLock.class);
RedisLockRegistry redisLockRegistry = (RedisLockRegistry) webApplicationContext.getBean(distributedLock.value());
Lock lock = redisLockRegistry.obtain(signature.getName() + "_" + args[0]);
boolean flag = false;
for (int i = 0; i < 3; i++) {
flag = lock.tryLock(distributedLock.time(), TimeUnit.SECONDS);
if(flag) {
break;
} else {
continue;
}
}
logger.info("获取锁:->" + flag);
Object proceed = null;
try {
proceed = point.proceed();
} catch (Exception e) {
logger.error(e.getMessage(),e);
} finally {
try{
lock.unlock();
} catch (Exception e) {
logger.error("无锁");
}
}
return proceed;
}
}
3. 业务接口层
public interface GrabService {
/**
* 司机抢单
* @param orderId
* @param driverId
* @return
*/
String grabOrder(int orderId , int driverId);
}
4.业务实现层
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Description 使用注解实现分布式锁
* @Author jzhao
* @Date 2021-3-6 11:01
**/
@Service
public class CloudServiceImpl implements GrabService {
private static Logger logger = LoggerFactory.getLogger(CloudServiceImpl.class);
@Autowired
OrderService orderService;
@Override
@DistributedLock(value = "redisLockRegistry", time = 10)
public String grabOrder(int orderId, int driverId) {
logger.info("司机:->" + driverId + "进行抢单");
// 添加业务代码
boolean flag = orderService.grab(orderId, driverId);
if(flag) {
logger.info("司机:->" + driverId + "抢单成功。");
} else {
logger.info("司机:->" + driverId + "抢单失败。");
}
return null;
}
}
本文介绍了如何基于`RedisLockRegistry`在Spring Boot中实现分布式锁。通过引用spring-integration,讨论了分布式锁的概念,并详细展开实战部分,包括pom配置、注解层、切面处理、业务接口及实现细节。
2568

被折叠的 条评论
为什么被折叠?



