aop解决对象连续两次触发的问题
一、定义注解
import java.lang.annotation.*;@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Deduplication {
String value();
}
二、定义aop类
import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class DeduplicationAspect {
private static final String CACHE_KEY = "deduplication";
@Autowired
private CacheService cacheService;//该处是缓存,可以用redis或者其他你能封装的缓存工具
@Pointcut("@annotation(deduplication)")//切面是有该注解的方法
public void deduplicateAop(Deduplication deduplication) {
}
/**
* 去重检查,并占位
*
* @param point
* @param deduplication
*/
@Before("deduplicateAop(deduplication)")
public void before(JoinPoint point, Deduplication deduplication) {
String key = this.getDeduplicationKey(deduplication);
Object o = cacheService.get(key);
if (o != null) {
throw new UnsupportedOperationException("请勿重复调用!");
}
cacheService.set(key, point.getArgs());
cacheService.expire(key, 60 * 5);
}
/**
* 去除占位
*
* @param point
* @param deduplication
*/
@AfterThrowing("deduplicateAop(deduplication)")
public void afterThrowing(JoinPoint point, Deduplication deduplication) {
this.deleteDeduplicationCache(deduplication);
}
/**
* 去除占位
*
* @param result
* @param deduplication
*/
@AfterReturning(returning = "result", pointcut = "deduplicateAop(deduplication)")
public void AfterReturning(Object result, Deduplication deduplication) {
this.deleteDeduplicationCache(deduplication);
}
/**
* 去除去重占位缓存
*
* @param deduplication
*/
private void deleteDeduplicationCache(Deduplication deduplication) {
String key = this.getDeduplicationKey(deduplication);
cacheService.delete(key);
}
/**
* 获取去重键值
*
* @param deduplication
* @return
*/
private String getDeduplicationKey(Deduplication deduplication) {
User currentUser = SecurityUtils.getCurrentUser();//这里是获取当前调用客户,根据使用情况而定
String uniqueHandler = deduplication.value();
return String.format("%s::%s::%s", CACHE_KEY, currentUser.getLogin(), uniqueHandler);
}
}
以上是 aop解决对象连续两次触发的问题 的全部内容, 来源链接: utcz.com/z/512220.html