springboot aop service层参数校验,日志输出等

╄→гoц情女王★ 提交于 2020-02-26 05:19:32

背景

我们通常用拦截器、过滤器、aop等功能在controller层实现参数的校验,日志输出,耗时统计等功能。但是有时候我们需要对外提供不同类型的接口,比如http接口和thrift接口,如果我们在controller层做这些配置,那么我们需要重复配置。为了到达复用性,我们可以将这些功能移到service层,因为service层是共用的。

方法

我们可以通过自定义注解 + aop 在service层实现这些功能

比如方法耗时统计:

首先定义一个注解:

package com.eco.annotation;

import java.lang.annotation.*;

/**
 * Created by zhanghuan on 2020/1/8.
 */
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationCostTime {
    String name() default "";
}

然后配置aop切入点:

package com.eco.aop;

import com.didichuxing.map_eco.dto.RealtimeFeaturesParam;
import com.didichuxing.map_eco.util.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Created by zhanghuan on 2020/1/8.
 */
@Aspect
@Component
@Slf4j
public class CostTimeAspect {
    private Long start = 0L;
    @Pointcut("@annotation(com.eco.annotation.OperationCostTime)")
    public void costTime(){}
    @Before("costTime()")
    public void doBefore(JoinPoint joinPoint){
        start = System.currentTimeMillis();
    }
    @After("costTime()")
    public void after(JoinPoint joinPoint){
        Long end = System.currentTimeMillis();
        Long ts = end - start;
        log.warn("class.method=" + joinPoint.getSignature().getDeclaringTypeName()
                +"."+joinPoint.getSignature().getName() + "()" + "||ts=" + ts);
    }

}

然后我们将注解绑定到方法上:

    @OperationCostTime
    @Validated
    public com.eco.dto.Result getFeaturesByLinkIds( @Validated RealtimeFeaturesParam realtimeFeaturesParam) {
        try {
            HTableInterface htable = realtimeFeaturesHBaseDataSource.getHTable();
            if (htable == null) {
                throw new RuntimeException("htable 获取失败");
            }
            JSONObject featureConfig = realtimeFeaturesApolloConfigGet.getRealtimeFeaturesConfig();
            Object result = null;
            String dataFormat = realtimeFeaturesParam.getDataFormat();
            if ("json".equals(dataFormat)) {
                result = getJsonData(realtimeFeaturesParam, htable, featureConfig);
            }else if("thrift".equals(dataFormat)){
                result = getThriftData(realtimeFeaturesParam,htable,featureConfig);
            }
            htable.close();
            return ResultUtil.success(result);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultUtil.error(-1,e.getMessage());
        }
    }

这样就可以了,参数校验注解已经实现好了,直接用Validated注解方法就可以了,如果参数是对象在参数前再加上Validated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!