序
最近項目裏整了一個通用的API日誌。感覺挺不錯的,整理一下分享出來。
接口大概時間圖如下:
分析
除了【業務處理】,其它的處理都與業務無關。可以考慮把通用的部分抽離出來,【業務處理】單獨處理。可以用兩種方案去處理。
方案
**1:**使用抽象類。提供一個方法,從【開始】處理到【結束】。【業務處理】設一個抽像方法(無實現)。每個接口都繼承抽象類。接口類重寫抽業務處理抽象方法。
**2:**使用AOP,開發人員只管【業務處理】。通過AOP的方式在【業務處理】包麪包一層日誌記錄。
對比兩種方案覺得AOP的方案更好。
1:AOP的方案,在前期不需要做寫日誌的擴展考慮,後期調整不需要調整原來的代碼。
2:AOP的方案,寫的代碼更優美,可擴展性更強。
AOP實現
1: 註釋,優美的代碼當然離不開註解,對註解情有獨鍾。
package com.ly.mp.swcas.main.config;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiTag {
String apiCode(); //接口編號
String apiName(); //接口描述
}
2:AOP
package com.ly.mp.swcas.main.config;
import com.google.gson.Gson;
import com.ly.mp.common.entities.RestResult;
import com.ly.mp.common.utils.BigDecimalUtils;
import com.ly.mp.swcas.main.entities.ApiLog;
import com.ly.mp.swcas.main.ibiz.IApiLogBiz;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;
@Aspect
@Component
public class ApiAspect {
private static final Logger logger = LoggerFactory.getLogger(ApiAspect.class);
@Autowired
IApiLogBiz logBiz;
/**
* 攔截註解的方法
*/
@Pointcut("@annotation(com.ly.mp.swcas.main.config.ApiTag)")
public void pointcutMethod() {
}
/**
* 流程
* 1:存儲數據到Log
* 2:執行業務處理方法
* 3:返回結果,保存Log
*
* @param joinPoint
* @return
*/
@Around("pointcutMethod()")
public RestResult around(ProceedingJoinPoint joinPoint) {
logger.debug("************攔截命中***************");
ApiLog apiLog = new ApiLog();
StopWatch watch = new StopWatch();
watch.start();
apiLog.setRequestTime(new Date());
ApiTag cfg = getApiTag(joinPoint);
apiLog.setApiCode(cfg.apiCode());
apiLog.setApiName(cfg.apiName());
apiLog.setRequestContent(joinPoint.getArgs()==null?"": new Gson().toJson(joinPoint.getArgs()));
apiLog.setId(UUID.randomUUID().toString());
apiLog.setCreatedDate(new Date());
apiLog.setIsEnable("1");
apiLog.setCreator("admin");
RestResult rs = new RestResult(0,"初始化");
try {
logger.info("**********執行業務方法**********");
rs = (RestResult) joinPoint.proceed();
apiLog.setRequestStatus(rs.getResult());
} catch (Throwable e) {
e.printStackTrace();
apiLog.setResponseContent(String.format("錯誤信息:%s",e.getMessage()));
apiLog.setRequestStatus(0);
}
watch.stop();
apiLog.setRequestCost(BigDecimalUtils.val(watch.getTotalTimeSeconds()));
apiLog.setResponseContent(new Gson().toJson(rs));
apiLog.setResponseTime(new Date());
logBiz.add(apiLog);
return rs;
}
private ApiTag getApiTag(ProceedingJoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
ApiTag rs;
Method[] methods = joinPoint.getTarget().getClass().getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
Annotation[] annotations = m.getDeclaredAnnotations();
for (Annotation a : annotations)
if (ApiTag.class.isInstance(a)) {
rs = (ApiTag) a;
return rs;
}
}
}
return null;
}
}
其中:
1: 這兩個註釋很關鍵,缺一不可,很多朋友說切面 切不中。。應該是姿勢不對。。(後面再細講)
@Aspect
//AOP 的聲明
@Component
//聲明本類是個組件,方便Spring boot 掃描
2: 攔截方法的規則,本例使用註解的方式去攔截。強列推薦使用註釋方式。
@Pointcut("@annotation(com.ly.mp.swcas.main.config.ApiTag)")
public void pointcutMethod() { }
3: 攔截的實現,沒什麼難懂的邏輯。
1)計時
2)訪問信息記錄到log
3) 調用【業務處理】的方法,這裏注意要加上try catch,以防哪個粗心大意的程序員直接拋出錯誤。
4)記錄結果
5)把【業務處理】的結果返回。
@Around("pointcutMethod()")
public RestResult around(ProceedingJoinPoint joinPoint) {
logger.debug("************攔截命中***************");
ApiLog apiLog = new ApiLog();
StopWatch watch = new StopWatch();
watch.start();
apiLog.setRequestTime(new Date());
ApiTag cfg = getApiTag(joinPoint);
apiLog.setApiCode(cfg.apiCode());
apiLog.setApiName(cfg.apiName());
apiLog.setRequestContent(joinPoint.getArgs()==null?"": new Gson().toJson(joinPoint.getArgs()));
apiLog.setId(UUID.randomUUID().toString());
apiLog.setCreatedDate(new Date());
apiLog.setIsEnable("1");
apiLog.setCreator("admin");
RestResult rs = new RestResult(0,"初始化");
try {
logger.info("**********執行業務方法**********");
rs = (RestResult) joinPoint.proceed();
apiLog.setRequestStatus(rs.getResult());
} catch (Throwable e) {
e.printStackTrace();
apiLog.setResponseContent(String.format("錯誤信息:%s",e.getMessage()));
apiLog.setRequestStatus(0);
}
watch.stop();
apiLog.setRequestCost(BigDecimalUtils.val(watch.getTotalTimeSeconds()));
apiLog.setResponseContent(new Gson().toJson(rs));
apiLog.setResponseTime(new Date());
logBiz.add(apiLog);
return rs;
}
APO實現起來就是那麼從容,自然。
3:啓動:
package com.ly.mp.swcas.main.config;
import com.ly.mp.common.web.LocalCommonInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import com.ly.mp.component.conf.cache.CachingConfig;
import javax.xml.ws.Endpoint;
@SpringBootApplication(exclude={ DataSourceAutoConfiguration.class,
XADataSourceAutoConfiguration.class, ActiveMQAutoConfiguration.class })
@Import({ LocalCommonInitializer.class, SwaggerConfiguration.class, CachingConfig.class, ApiAspect.class })
@PropertySource({"classpath:ly-swcas.properties","classpath:application.properties"})
@ImportResource({"classpath:main-api.xml"})
@ComponentScan(basePackages={"com.ly.mp.swcas.main.api"})
public class MainApi {
public static void main(String[] args)
{
System.setProperty("service.name", "ly.mp.swcas.main.api");
SpringApplication.run(MainApi.class, args);
}
}
關鍵:
ApiAspect 切點的類必須在啓動的時候掃描 ,所以ApiAspect 必須使用@Component 註解。那些說切不中的基本上都是因爲 這個問題。
可以通過以下兩種方式去掃描:
1):
@Import({ LocalCommonInitializer.class, SwaggerConfiguration.class, CachingConfig.class, ApiAspect.class })
2):
@ComponentScan({"com.ly.mp.swcas.main.config")
最後
看一下效果