只是一个demo展示。设置一个统一的返回值对象
Result类。 然后执行时间(接口消耗时间)和 当前时间通过AOP插入
package com.tian.billsystem.config.result;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
/**
* @author 邓天天
* @date 2021/3/16 20:13
* 统一返回值对象
*/
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result {
private Result(){}
private Integer errorCode;
private String errorMsg;
private Long executionTime;
private String machineName;
private Date time;
private Object data;
public static Result success(Object object) {
Result result = new Result();
result.setData(object);
result.setErrorCode(0);
result.setErrorMsg("执行成功");
result.setMachineName(getMachine());
return result;
}
public static Result success() {
return success(null);
}
public static Result error() {
Result result = new Result();
result.setErrorCode(-1);
result.setErrorMsg("执行失败");
result.setMachineName(getMachine());
return result;
}
public Result data(Object o) {
this.setData(o);
return this;
}
public Result errorCode(Integer errorCode) {
this.setErrorCode(errorCode);
return this;
}
public Result errorMsg(String msg) {
this.setErrorMsg(msg);
return this;
}
public Result executionTime(long executionTime) {
this.setExecutionTime(executionTime);
return this;
}
public static String getMachine() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "获取机器名字失败";
}
}
}
利用AOP插入当前时间和计算执行时间
package com.tian.billsystem.config;
import com.tian.billsystem.config.result.Result;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author 邓天天
* @date 2021/3/16 20:56
*/
@Aspect
@Component
public class WebAspect {
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.tian.billsystem.controller.*.*(..))")
public void pointCut() {
// 只是作为一个切入点,没有实际意义
}
@Before("pointCut()")
public void before() {
startTime.set(System.currentTimeMillis());
}
@AfterReturning(returning = "result",pointcut = "pointCut()")
public void doAfterReturning(Result result) {
// 计算消耗的时间
result.setExecutionTime(System.currentTimeMillis()-startTime.get());
// 插入当前时间
result.setTime(new Date());
startTime.remove();
}
}
使用示例
@PostMapping("/student")
public Result student(@RequestBody Student student) {
return Result.success(student);
}
测试结果
{
"errorCode": 0,
"errorMsg": "执行成功",
"executionTime": 17,
"machineName": "LAPTOP-T50JTJHJ",
"time": "2021-03-16T13:13:38.992+00:00",
"data": {
"name": "五更依旧朝花落",
"sex": "男",
"year": 52,
"createDate": "2021-03-15T00:00:00.000+00:00",
"hobby": [
"蹴鞠",
"足球"
]
}
}