Tic*_*ker 5 java json spring-cloud-feign feign
在我的应用程序中,我必须从列表中知道哪些服务器地址已启动。我找到的解决方案是从 Spring-Boot Actuator 调用每个健康端点。JSon 响应是:
{
"status": "UP"
}
Run Code Online (Sandbox Code Playgroud)
在应用程序的其他部分,我使用 Spring-Cloud 中通过@FeignClient注释定义的 Feign 客户端,效果非常好:
@FeignClient(
name = "tokenProxy",
url = "${host}:${port}"
)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这种配置不允许重复使用相同的客户端来调用不同地址上的相同端点。所以我必须定义我自己的自定义客户端(如果有其他解决方案,请随时告诉我!):
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用端点时/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]
Run Code Online (Sandbox Code Playgroud)
我想我应该使用 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>
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我,为我的需求提供更好的解决方案,或者解释如何正确配置自定义 Feign 客户端吗?
提前致谢
事实上,在使用 spring-cloud 依赖项时,默认情况下不会加载包含 Jackson 解码器和编码器的库。要解决这个问题,我只需将以下内容添加到我的pom.xml文件中:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18223 次 |
| 最近记录: |