添加依赖
<!-- 添加redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 添加aop依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 添加jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
配置redis(application-redis.properties)
spring.redis.host=localhost
spring.redis.port=6379
redis.host=localhost
redis.port=6379
配置redis(RedisConfig)
@Configuration
@PropertySource("classpath:/application-redis.properties")
public class RedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Bean
public Jedis jedis(){
return new Jedis(host,port);
}
}
自定义注解(NoRepeatSubmit)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
/**
* 指定时间内不可重复提交,单位毫秒秒
* @return
*/
int timeOut() default 3000;
}
AOP(RepeatSubmit)
@Aspect
@Component
public class RepeatSubmit {
@Around("@annotation(noRepeatSubmit)")
public Object around(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit){
// 获取注解
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 获取类,方法
String className = method.getDeclaringClass().getName();
String methodName = method.getName();
// 组装key用户唯一标识+操作和方法
String key = "tokenKey" + className + methodName;
// 获取超时时间
int timeOut = noRepeatSubmit.timeOut();
// 创建对象 判断key值是否存在 无则抛出 有则添加redis缓存中 设置时间失效
Jedis jedis = new Jedis();
if (jedis.exists(key)){
System.out.println("请勿重复请求拦截");
throw new RuntimeException("请勿重复请求拦截");
}else{
jedis.set(key,"请求成功");
System.out.println("请求成功");
jedis.pexpire(key,timeOut);
}
Object proceed = null;
try {
proceed = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return proceed;
}
}
controller使用
@RestController
public class MessageController {
@CrossOrigin
@DeleteMapping("deleteMessage")
@NoRepeatSubmit(timeOut = 3000)
public String deleteMessage(@RequestBody Message message){
int i = messageService.deleteMusic(message.getId());
if (i>=1){
return "数据删除成功";
}else {
return "数据删除失败,请重试!";
}
}
@CrossOrigin
@PostMapping("updateMessage")
@NoRepeatSubmit(timeOut = 3000)
public String updateMessage(@RequestBody Message message){
if(message.getSex().equals("男")){
message.setSex("1");
}else if (message.getSex().equals("女")){
message.setSex("2");
}
int i = messageService.updateMusic(message);
if (i>=1){
return "数据修改成功";
}else {
return "数据修改失败,请重试!";
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。