1.主要依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.12.1</version>
</dependency>
- 配置redission
import cn.com.yeexun.core.utils.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissionConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int database;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient getRedisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port)
.setDatabase(database);
if (StringUtils.isNotEmpty(password)) {
config.useSingleServer().setAddress("redis://" + host + ":" + port).setDatabase(database)
.setPassword(password);
} else {
config.useSingleServer().setAddress("redis://" + host + ":" + port).setDatabase(database);
}
//设置全局默认看门狗机续期时间,如果在使用时不设置,则使用全局的,如果全局不设置,则使用默认的30000,单位毫秒
config.setLockWatchdogTimeout(2000);
return Redisson.create(config);
}
}
- 自定义注解
import javax.validation.constraints.NotNull;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @author lvyuanbo
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RedissionLock {
/**
* 分布式锁的key
*/
@NotNull
String keyPrefix();
/**
* 类型,例如:收藏 评论等
*/
@NotNull
String type();
/**
* 获取锁等待时间(默认两秒,还没获取到锁即放弃)
*/
long waitTime() default 2;
/**
* 过期时长,防止一直占用锁
*/
long expire() default 10;
/**
* 过期时长单位
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;
}
- sepl工具类
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.lang.reflect.Method;
import java.util.Optional;
public class SpElUtils {
private static final ExpressionParser parser = new SpelExpressionParser();
private static final DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
public static String parseSpEl(Method method, Object[] args, String spEl) {
String[] params = Optional.ofNullable(parameterNameDiscoverer.getParameterNames(method)).orElse(new String[]{});//解析参数名
EvaluationContext context = new StandardEvaluationContext();//el解析需要的上下文对象
for (int i = 0; i < params.length; i++) {
context.setVariable(params[i], args[i]);//所有参数都作为原材料扔进去
}
Expression expression = parser.parseExpression(spEl);
return expression.getValue(context, String.class);
}
}
- aop
import cn.com.yeexun.common.redis.annotation.RedissionLock;
import cn.com.yeexun.common.redis.utils.SpElUtils;
import cn.com.yeexun.core.exception.BizException;
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.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Method;
@Aspect
@Component
public class RedissionAspect {
private static final Logger logger = LoggerFactory.getLogger(RedissionAspect.class);
@Resource
private RedissonClient redissonClient;
@Around("@annotation(redissionLock)")
public Object lock(ProceedingJoinPoint proceedingJoinPoint, RedissionLock redissionLock) {
Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
String key = SpElUtils.parseSpEl(method, proceedingJoinPoint.getArgs(), redissionLock.keyPrefix());
String lockKey = String.format("lock:%s:%s", key, redissionLock.type());
RLock lock = redissonClient.getLock(lockKey);
boolean hasLock = false;
try {
hasLock = lock.tryLock(redissionLock.waitTime(), redissionLock.expire(), redissionLock.timeUnit());
if (hasLock) {
return proceedingJoinPoint.proceed();
}
} catch (Throwable throwable) {
logger.error(throwable.getMessage());
throw new BizException(throwable.getMessage());
} finally {
if (hasLock) {
lock.unlock();
}
}
throw new BizException("获取分布式锁失败");
}
}
6. serviceImpl使用
@Override
@RedissionLock(keyPrefix = "#contentId", type = "likeOrDowns")
public void likeOrDowns(Long contentId, String type) {
//处理逻辑
}