SpringCloud OpenFeign 自定義響應解碼器的問題記錄
一、JsonResult 在 OpenFeign 微服務調用的問題
我們在使用 Spring Cloud 微服務的時候,通常將返回結果使用一個JsonResult 類進行封裝,例如如下的格式:
public class JsonResult<T> {
/* 響應碼,200為成功 */
private Integer code;
/* 失敗時的具體失敗信息 */
private String message;
/* 成功時的數(shù)據(jù)對象 */
private T data;
}
而調用方在使用Spring Cloud OpenFeign定義的客戶端調用遠程服務時,由于遠程微服務接口的返回值也是 JsonResult 對象,這樣本地的接口也需要使用 JsonResult 進行接收,這增加了額外的Result類重新拆開等工作。
有沒有辦法實現(xiàn)一些自定義的邏輯,比如將統(tǒng)一返回的Result類重新拆開僅返回對應的業(yè)務對象,或者對特定的響應碼進行處理等等?
二、自定義 OpenFeign 響應解碼器
為了實現(xiàn)上述功能,我們就需要改造默認的Decoder。Spring Cloud OpenFeign允許我們在定義一個FeignClient 的時候,指定一個額外的配置類,比如:
@FeignClient(
name = "xxx-base",
path = "/api/base",
configuration = CustomizedConfiguration.class /* 自定義配置類 */
)
public interface RemoteUserService {
//..
}我們可以在 CustomizedConfiguration 中定義一個自己的 Decoder 來覆蓋默認的配置。
Spring Cloud 對 Feign的封裝和默認配置可以查看官方文檔。
自定義的 Decoder 需要實現(xiàn)feign.codec.Decoder接口,也可以參考默認的Decoder的實現(xiàn)邏輯(org.springframework.cloud.openfeign.support.ResponseEntityDecoder),
下面的實現(xiàn)可以對統(tǒng)一返回值Result類的解包,并對異常返回進行處理:
public class CustomizedConfiguration{
@Bean
public Decoder feignDecoder() {
return new OpenFeignResultDecoder();
}
}public class OpenFeignResultDecoder implements Decoder {
@Resource
ObjectMapper objectMapper;
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
String resultJson = this.getResponseBody(response);
try {
JavaType rawType = objectMapper.getTypeFactory().constructType(type);
JavaType resultType = objectMapper.getTypeFactory().constructParametricType(JsonResult.class, rawType.getRawClass());
JsonResult<?> jsonResult = objectMapper.readValue(resultJson, resultType );
if (jsonResult.getCode() != HttpStatus.OK.value()){
throw new DecodeException(
response.status(),
jsonResult.getMessage(),
response.request());
}
return jsonResult.getData();
} catch (Exception ex){
throw new IllegalArgumentException("對象轉換失敗: " + ex.getMessage());
}
}
/*
* 將 response body 解析為 string
*/
private static String getResponseBody(Response response) throws IOException {
Response.Body resBody = response.body();
if (Objects.isNull(resBody)){
throw new DecodeException(
response.status(),
"返回體為空",
response.request());
}
String jsonStr;
char[] buffer = new char[1024*4];
int len;
try (
Reader reader = resBody.asReader(StandardCharsets.UTF_8);
StringWriter strWriter = new StringWriter()
){
while ((len = reader.read(buffer)) != -1){
strWriter.write(buffer, 0, len);
}
jsonStr= strWriter.toString();
}
return jsonStr;
}
}實現(xiàn)了Decoder之后,只需要將其配置到CustomizedConfiguration中即可。
三、為 FeignClient 注冊全局配置
注意如果CustomizedConfiguration添加了@Configuration的注解,則會成為Feign Client構建的默認配置,這樣就不需要在每個@FeignClient注解中都去指定配置類了:
@Configuration
public class OpenFeignConfig {
@Bean
public Decoder feignDecoder() {
return new OpenFeignResultDecoder();
}
}@FeignClient(
name = "xxx-base",
path = "/api/base"
)
public interface RemoteUserService {
//..
}四、使用 OpenFeign 遠程服務示例
添加了自定義的Decoder之后,如果一個遠程接口的定義是這樣的:
@FeignClient(
name = "xxx-base",
path = "/api/base"
)
public interface RemoteUserService {
@GetMapping(value = "/user/detail/{userId}")
public User getUserDetailById(@PathVariable Integer userId)
}// ...
@Resource
RemouteUserService userService
public void demoUserService(int userId){
User user = userService.getUserDetailById(userId);
// ....
}
到此這篇關于SpringCloud OpenFeign 自定義響應解碼器的文章就介紹到這了,更多相關SpringCloud OpenFeign解碼器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
maven中的maven-antrun-plugin插件示例詳解
maven-antrun-plugin?是?Maven?生態(tài)中一個強大的工具,尤其適合需要復用?Ant?腳本或實現(xiàn)復雜構建邏輯的場景,然而,過度使用可能導致構建腳本復雜化,建議權衡利弊后合理使用,這篇文章主要介紹了maven中的maven-antrun-plugin插件詳解,需要的朋友可以參考下2025-06-06
logback中顯示mybatis查詢日志文件并寫入的方法示例
這篇文章主要為大家介紹了logback中顯示mybatis查詢日志文件并寫入的方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03
hibernate 配置數(shù)據(jù)庫方言的實現(xiàn)方法
這篇文章主要介紹了hibernate 配置數(shù)據(jù)庫方言的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
IDEA配置Tomcat后,控制臺tomcat?catalina?log出現(xiàn)亂碼問題
本文介紹了如何通過設置Tomcat和IDEA的編碼格式來解決編碼問題,首先嘗試修改Tomcat的logging.properties文件中的編碼設置,如果未解決問題,則調整IDEA的編碼設置,通過修改vmoptions文件來全局設置IDEA的編碼格式,作者分享了個人成功解決問題的方法和步驟,供其他開發(fā)者參考2024-09-09

