360免费自助建站疫情防控最新数据
一、前言
假设有以下需求:
- 服务消费者A调用服务提供者B往MySQL新增一条人员信息
- 服务提供者做了一个逻辑判断:若无该人员信息则新增,若已存在该人员信息,则返回给消费者异常状态码及异常信息:“请勿添加重复数据”
问题:
- 通常新增、修改、删除服务无需返回,所以服务消费者无法获取服务提供者返回的异常状态码和异常信息
- 对返回结果的封装一般在服务消费者,对公共接口的服务提供者通常不会做返回值封装
二、解决思路
- 封装一个返回实体,作用于fegin调用时返回
三、实现
- 返回实体
/*** 返回实体** @author Odinpeng* @since 2023/12/5*/
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;@Data
public class ResponseBody<T> {/*** 输出信息*/private String msg;/*** 返回数据*/@Builder.Default@JsonInclude(JsonInclude.Include.NON_NULL)private T body = null;/*** 状态码*/private int code;/*** 默认构造成功信息*/public ResponseBody() {this.code = ReturnStatus.SUCCESS.getVal();this.msg = ReturnStatus.SUCCESS.getMsg();}public ResponseBody(int code, String msg) {this.code = code;this.msg = msg;}public ResponseBody(int code, String msg, T body) {this.code = code;this.msg = msg;this.body = body;}public static <T> ResponseBody<T> success() {return new ResponseBody<>();}public static <T> ResponseBody<T> success(String msg) {return new ResponseBody<>(ReturnStatus.SUCCESS.getVal(), msg);}public static <T> ResponseBody<T> error(int code, String msg) {return new ResponseBody<>(code, msg);}public static <T> ResponseBody<T> error(String msg) {return new ResponseBody<>(ReturnStatus.ERROR.getVal(), msg);}public ResponseBody<T> code(int code) {this.code = code;return this;}public ResponseBody<T> msg(String msg) {this.msg = msg;return this;}public ResponseBody<T> body(T body) {this.body = body;return this;}
}@Getter
enum ReturnStatus {/*** 操作成功*/SUCCESS(200, "操作成功"),/*** 系统内部错误*/ERROR(500, "系统内部错误");/*** 状态*/private final int val;/*** 信息输出*/private final String msg;/*** 有参构造** @param val 状态码* @param msg 消息体*/ReturnStatus(int val, String msg) {this.val = val;this.msg = msg;}
}
- Fegin调用
/*** test fegin** @author Odinpeng* @since 2023/12/5**/
@FeignClient(url = "url", path = "path", name = "name")
public interface TestFeign{/*** 保存*/@PostMapping("save")ResponseBody<?> save(@RequestBody Body body);/*** 修改*/@PostMapping("update")ResponseBody<?> update(@RequestBody Body body);/*** 删除*/@PostMapping("delete")ResponseBody<?> delete(@RequestBody Integer index);
}