接口过期过滤器

注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 过期接口通知
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface ExpiredInterface {
    /** 接口删除时间戳 */
    String deadline() default "2023-06-30";

    /** 是否抛出异常信息 */
    boolean throwError() default false;

    /** 新接口信息 */
    String newInterface() default "";

    /** 返回的提示信息 */
    String msg() default "接口已过期,请更换接口!";
}

过滤器

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.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description : 过期接口通知过滤器
 * @Author : cxw
 * @Date : 2022/11/30 10:56
 * @Version : 1.0
 **/
@Component
@Aspect
@Order(100)
public class ExpiredInterfaceFilter {

    Logger logger= LoggerFactory.getLogger(ExpiredInterfaceFilter.class);

    // 定义 注解 类型的切点
    @Pointcut("@annotation(ExpiredInterface)|| @within(ExpiredInterface)")
    public void arrPointcut() {}

    // 实现过期接口功能
    @Around("arrPointcut()")
    public Object arrBusiness(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法的 AvoidRepeatRequest 注解
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        ExpiredInterface annotation = method.getAnnotation(ExpiredInterface.class);
        if(annotation==null){
            annotation = joinPoint.getTarget().getClass().getAnnotation(ExpiredInterface.class);
        }
        if(annotation!=null){
            logger.error(annotation.msg()+"接口删除时间节点:"+annotation.deadline() +" 请使用新接口: "+annotation.newInterface());
        }
        String expiredInterfaceFilter = System.getProperty("ExpiredInterfaceFilter");
        if(annotation.throwError()||isDebug(expiredInterfaceFilter)){
            throw new Exception(annotation.msg()+"接口删除时间节点:"+new Date(annotation.deadline()) +" 请使用新接口: "+annotation.newInterface());
        }
        return joinPoint.proceed();
    }

    /**
     * 判断是否抛出异常
     * @param expiredInterfaceFilter
     * @return
     */
    private boolean isDebug(String expiredInterfaceFilter) {
        if(StringUtils.isEmpty(expiredInterfaceFilter))return false;
        if(expiredInterfaceFilter.equals("throwError"))return true;
        return false;
    }
}

 

posted @ 2023-04-28 13:33  扰扰  阅读(3)  评论(0编辑  收藏  举报