【代码优化与重构技巧】运用注解实现重构后新老代码的切换

  • Post author:
  • Post category:其他




说明

负责的项目,涉及到4个接口、10+个项目调用,日调用量2亿左右。

在重构前4个接口,分接口调用,但重复性代码比较多,有定制化的处理。所以需要将4个接口重构优化为1个接口。

因为涉及到多接口、多调用方和调用量大多问题,所以为了在做新老切换时,降低上线的风险,需要通过流量、项目渠道做新老切换。



注解

在方法上写上注解,可以直接实现切面处理。

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



切面

通过切面控制流量、根据项目渠道来切换调用。

@Aspect
@Slf4j
@Component
public class OpQueryInterfaceAspect {

    @Value("${opQuery.flowStrategy.switch:true}")
    private boolean interfaceSwitch;

    @Value("${opQuery.flowStrategy.maxPermillage:-1}")
    private int maxPermillage;

    @Resource
    private OpQueryController opQueryController;

    @Value("${opQuery.flowStrategy.appIds:,,}")
    private String interfaceAppIds;

    @Around("@annotation(opQueryChangeInterface)")
    public Object aroundPoint(ProceedingJoinPoint pjp, OpQueryChangeInterface opQueryChangeInterface) throws Throwable {
        if (interfaceSwitch) {
            return pjp.proceed();
        }
        
        //值越大,切面到新代码的量就越大
        if (FlowStrategy.getInstance().selectPermillage(maxPermillage)) {
            return pjp.proceed();
        }

        Object[] args = pjp.getArgs();
        OpQueryRequest opQueryRequest = (OpQueryRequest) args[0];

        if (opQueryRequest != null) {
            String appId = opQueryRequest.getAppId();
            if (StringUtils.isNotBlank(appId) && interfaceAppIds.contains("," + appId + ",")) {
                HttpServletRequest request = (HttpServletRequest) args[1];
                return opQueryController.queryData(opQueryRequest, request);
            }
        }
        return pjp.proceed();
    }
}



控制流量方法

使用随机数来实现控制流量。

public class FlowStrategy {

    private FlowStrategy(){}

    public static class FlowStrategySingleton{
        public static FlowStrategy flowStrategy = new FlowStrategy();
    }

    public static FlowStrategy getInstance(){
        return FlowStrategySingleton.flowStrategy;
    }

    /**
     * @param targetPermillage 千分率上限
     * @return
     */
    public boolean selectPermillage(int targetPermillage){
        int permillage=(int)Math.ceil(Math.random() * 1000);
        return permillage>targetPermillage;
    }
    /**
     * @param targetPercentage 百分率上限
     * @return
     */
    public boolean selectPercentage(int targetPercentage){
        int permillage=(int)Math.ceil(Math.random() * 100);
        return permillage>targetPercentage;
    }

    public static void main(String[] args) {
        new FlowStrategy().selectPermillage(10);
    }
}



使用注解

在方法上使用注解切换。

@PostMapping(value = "query",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@OpQueryChangeInterface
public String queryTakingCollData(@RequestBody OpQueryRequest opQueryRequest, HttpServletRequest request) {
	return "";
}



版权声明:本文为weixin_42246822原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。