json統一返回格式
阿新 • • 發佈:2018-11-24
參考自:Java秒殺系統方案優化-高效能高併發實戰
一般我們會使用這樣的封裝
public class Result<T> {
private int code;
private String msg;
private T data;
}
但是這樣封裝的壞處
1.使用不方便(每次都需要new),我們呼叫者只關心成功時返回什麼資料,失敗時code及msg
2.不能保證code和msg統一(多人協同開發時)
針對第一條我們改進為
public class Result<T> {
private int code;
private String msg;
private T data;
/**
* 成功時候的呼叫
* */
public static <T> Result<T> success(T data){
return new Result<T>(data);
}
}
針對第二條我們的做法是封裝一個CodeMsg
public class CodeMsg { private int code; private String msg; //通用異常 public static CodeMsg SUCCESS = new CodeMsg(0, "success"); public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服務端異常"); //登入模組 5002XX //商品模組 5003XX //訂單模組 5004XX //秒殺模組 5005XX private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } }
所以最後我們的程式碼
public class CodeMsg { private int code; private String msg; //通用異常 public static CodeMsg SUCCESS = new CodeMsg(0, "success"); public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服務端異常"); //登入模組 5002XX //商品模組 5003XX //訂單模組 5004XX //秒殺模組 5005XX private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } }
public class Result<T> {
private int code;
private String msg;
private T data;
/**
* 成功時候的呼叫
* */
public static <T> Result<T> success(T data){
return new Result<T>(data);
}
/**
* 失敗時候的呼叫
* */
public static <T> Result<T> error(CodeMsg cm){
return new Result<T>(cm);
}
private Result(T data) {
this.code = 0;
this.msg = "success";
this.data = data;
}
private Result(CodeMsg cm) {
if(cm == null) {
return;
}
this.code = cm.getCode();
this.msg = cm.getMsg();
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
}