![](/img/trans.png)
[英]Feign client and how to cast JSON-response to Application/Unencoded
[英]How to decode JSon response with custom Feign client?
在我的應用程序中,我必須從列表中知道一個服務器地址,這些地址已啟動。 我找到的解決方案是從 Spring-Boot 執行器中為每個執行器調用健康端點。 JSon 響應為:
{
"status": "UP"
}
在應用程序的其他部分,我使用來自 Spring-Cloud 的 Feign 客戶端,它使用@FeignClient
注釋定義,效果很好:
@FeignClient(
name = "tokenProxy",
url = "${host}:${port}"
)
不幸的是,這種配置不允許重復使用同一個客戶端來調用不同地址上的同一個端點。 所以我必須定義自己的自定義客戶端(如果有其他解決方案,請隨時告訴我:):
@GetMapping(
value = "/servers"
)
public Server discover() {
MyClient myClient = Feign.builder()
.target(
Target.EmptyTarget.create(
MyClient.class
)
);
return myClient.internalPing(URI.create("http://localhost:8090"));
}
interface MyClient {
@RequestLine("GET /actuator/health")
Server internalPing(URI baseUrl);
}
class Server {
private final String status;
@JsonCreator
public Server(@JsonProperty("status") String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
當我調用端點/servers
時,我收到以下錯誤,表明我的自定義 Feign 客戶端未配置適當的解碼器:
feign.codec.DecodeException: class com.xxx.web.Server is not a type supported by this decoder.
at feign.codec.StringDecoder.decode(StringDecoder.java:34) ~[feign-core-10.10.1.jar:na]
at feign.codec.Decoder$Default.decode(Decoder.java:92) ~[feign-core-10.10.1.jar:na]
at feign.AsyncResponseHandler.decode(AsyncResponseHandler.java:115) ~[feign-core-10.10.1.jar:na]
at feign.AsyncResponseHandler.handleResponse(AsyncResponseHandler.java:87) ~[feign-core-10.10.1.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:138) ~[feign-core-10.10.1.jar:na]
我想我應該使用 JacksonDecoder,但我在 Spring-Cloud Hoxton.SR5
的依賴項中找不到它:
<dependencies>
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
...
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencyManagement>
有人可以幫助我,為我的需要提供更好的解決方案,或者解釋如何正確配置自定義 Feign 客戶端?
提前致謝
事實上,使用 spring-cloud 依賴時,默認沒有加載包含 Jackson 解碼器和編碼器的庫。 要解決此問題,我只需將以下內容添加到我的pom.xml
文件中:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
</dependency>
另一種方法是使用 @Import @Import(FeignClientsConfiguration.class)
注釋 class,這是 Spring Cloud Netflix 提供的默認配置。
那么在創建 Feign 客戶端的時候注入 Encoder 和 Decoder 就變得很容易了:
@Import(FeignClientsConfiguration.class)
@Configuration
public class MyConfiguration {
(...)
Myclient myClient (Decoder feignDecoder, Encoder feignEncoder) {
return Feign.builder()
.decoder( feignDecoder )
.encoder( feignEncoder )
.target(
Target.EmptyTarget.create(
MyClient.class
)
);
}
class 配置中有兩種不同的定義編碼器(可分頁或不可分頁),因此請注意通過名稱或限定符清楚地識別您想要的編碼器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.