统一返回封装类ResponseResult
1、 ResponseResult
java
复制代码
/**
* @author: yc
* @des: 统一返回封装类
* @date: 2024/08/07 14:08
*/
@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
java
复制代码
@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依赖
xml
复制代码
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
3.2 ResponseTimeAspect
java
复制代码
/**
* @author: yc
* @des: 统一响应类处理
* @date: 2024/08/07 14:15
*/
@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
java
复制代码
/**
* @author: yc
* @des: 测试
* @date: 2024/08/07 13:58
*/
@RestController
@RequestMapping("test")
public class TestController {
@PostMapping("hello")
public ResponseResult<String> hello(){
return ResponseResult.data("hello");
}
}
5、结果截图