统一返回封装类ResponseResult
1、 ResponseResult
@Data
@NoArgsConstructor
public class ResponseResult<T> {
private String requestTime;
private String responseTime;
private int code;
private String msg;
private String takeTime;
private T data;
private int total;
public ResponseResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
if (data instanceof Collection) {
this.total = ((Collection<?>) data).size();
}
}
public static <T> ResponseResult<T> fail(Integer code,String msg) {
return new ResponseResult<>(code, msg, null);
}
public static <T> ResponseResult<T> data(T data) {
return data(data,Constant.DEFAULT_NULL_MESSAGE);
}
public static <T> ResponseResult<T> data(T data, String msg) {
return data(RespBizCodeEnum.BIZ_0.getCode(), data, msg);
}
public static <T> ResponseResult<T> data(int code, T data, String msg) {
return new ResponseResult<>(code, data == null ? Constant.DEFAULT_NULL_MESSAGE : msg, data);
}
}
2、返回状态枚举RespBizCodeEnum
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RespBizCodeEnum {
BIZ_0(0, "成功"),
BIZ_10001(10001, "不符合要求的请求参数,具体说明参考msg"),
BIZ_10002(10002, "完成,但没有数据"),
BIZ_10003(10003, "无权限,请求要求身份验证"),
BIZ_10004(10004, "IP未设置白名单"),
BIZ_10005(10005, "禁止访问"),
BIZ_20001(20001, "无该用户"),
BIZ_20002(20002, "密码错误"),
BIZ_30001(30001, "该业务未实现"),
BIZ_99900(99900, "程序执行异常,msg中程序的异常信息"),
BIZ_99999(99999, "服务器遇到错误,无法完成请求,查看msg,或联系运维人员"),
;
private Integer code;
private String msg;
}
3、统一响应类处理AOP
3.1 aspectj pom依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
3.2 ResponseTimeAspect
@Aspect
@Component
public class ResponseTimeAspect {
@Around("execution(* com.yc.core.controller..*.*(..))")
public Object disposeResponseResult(ProceedingJoinPoint joinPoint) throws Throwable {
String startTimeStr = DateUtil.date().toString();
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
String endTimeStr = DateUtil.date().toString();
long endTime = System.currentTimeMillis();
long responseTime = endTime - startTime;
if (result instanceof ResponseResult) {
((ResponseResult<?>) result).setRequestTime(startTimeStr);
((ResponseResult<?>) result).setResponseTime(endTimeStr);
((ResponseResult<?>) result).setTakeTime(String.valueOf(responseTime));
}
return result;
}
}
4、controllrt
@RestController
@RequestMapping("test")
public class TestController {
@PostMapping("hello")
public ResponseResult<String> hello(){
return ResponseResult.data("hello");
}
}
5、结果截图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/cbdbb296b1cd47c3b2e659094f6e0e1d.png)