栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义注解及使用场景

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义注解及使用场景

1 概念

Target:描述了注解修饰的对象范围,取值在java.lang.annotation.ElementType定义,

  • METHOD:用于描述方法
  • PACKAGE:用于描述包
  • PARAMETER:用于描述方法变量
  • TYPE:用于描述类、接口或enum类型

Retention: 表示注解保留时间长短。取值在java.lang.annotation.RetentionPolicy中,取值为:

  • SOURCE:在源文件中有效,编译过程中会被忽略
  • CLASS:随源文件一起编译在class文件中,运行时忽略
  • RUNTIME:在运行时有效

只有定义为RetentionPolicy.RUNTIME时,我们才能通过注解反射获取到注解。

2 重试注解

(1)定义重试注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryAnnotation {

    int retryTimes() default 0 ;

    
    MidBackoff backoff() default @MidBackoff();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface MidBackoff {

    
    int count() default 10;

    
    double multiplier() default 0;

    
    int delay() default 0;
}

(2)重试切面

@RefreshScope
@Component
@Aspect
@Slf4j
public abstract class RetryAspect {

    // 切入点
    @Pointcut("@annotation(com.sr.bizmid.tradeCore.common.annotation.RetryAnnotation)")
    public void pointCut() {
    }

    // joinPoint 连接点
    @Around("pointCut()")
    public Object process(ProceedingJoinPoint joinPoint, RetryAnnotation retryAnnotation) throws Throwable {
        AtomicReference proceed = new AtomicReference<>();
        Signature signature = joinPoint.getSignature();
        String name = signature.getName();
        Class targetClass = signature.getDeclaringType();
        final Object[] args = joinPoint.getArgs();
        try {
            retryTemplate.execute(context -> {
                try {
                      // 执行被代理对象的方法
                      proceed.set(joinPoint.proceed());
                } catch (Exception e) {
                    log.error("RetryAspect retryError className:{}  method:{} args:{}",targetClass.getName(),name, JSON.toJSonString(args),e);
                    throw e;
                }
                return null;
            });

        } catch (Exception e) {
            log.error("RetryAspect retryFinishError className:{}  method:{} args:{}",targetClass.getName(),name,JSON.toJSonString(args),e);
            //加入重试表重试(重试逻辑)
            saveRetryRecord(joinPoint, retryAnnotation);
            throw new TRetailSystemException(TradebaseErrorCode.TRADE_CORE_RETRY_ASPECT_ERROR,e);
        }
        return proceed.get();
    }
} 

(3)RPC 调用使用重试注解

    @RetryAnnotation(backoff = @MidBackoff(count = 5,multiplier = 1,delay = 30))
    public void writeOFFCoupon(OperateCouponsRequest operateCouponsRequest){
   
        HttpResult httpResult;
        try {
            log.info("调用核销优惠券请求入参:{}", JSON.toJSonString(operateCouponsRequest));
            httpResult = couponClient.operateCoupons(operateCouponsRequest);
            log.info("调用核销优惠券请求response:{}", JSON.toJSonString(httpResult));
        }catch (Exception e) {
            throw new TRetailRpcResultException(TradeRpcErrorCode.TRADE_CALL_COUPON_ERROR, e);
        }
        if (!httpResult.isSuccess() || httpResult.getData() == null) {
            throw new TRetailRpcResultException(TradeRpcErrorCode.TRADE_CALL_COUPON_ERROR);
        }
    }
3 商品校验注解

(1)定义注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SettleCheck {}

(2)校验切面

public class ValidatorAspect{

    @Pointcut("@annotation(com.sr.bizmid.tradeCore.common.annotation.SettleCheck)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public void process(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        Class targetClass = signature.getDeclaringType();
        if (checkHavingValidGoods() || checkWhetherLimitCheck()) {
            log.warn("存在无效商品: 组件类名为:{}", targetClass.getSimpleName());
            return;
        }
        joinPoint.proceed();
    }

}

(3)商品操作前,基于注解执行校验逻辑

@Component
public class CommodityPrescriptionBuilder {

    @SettleCheck
    public void buildDomain() {
          
        // 商品操作逻辑
       
    }

}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号