问题描述
我正在尝试将Sleuth集成到我们的系统中.如果我使用带@FeignClient
注释的接口,则一切正常.这些接口会自动进行检测,并且Sleuth标头会通过REST调用传播.
I'm trying to integrate Sleuth into our system. If I use interfaces annotated with @FeignClient
, everything works fine. These interfaces get instrumented automatically, and Sleuth headers get propagated with REST calls.
但是,我们有一些现有代码直接使用Feign.Builder和Feign带注释的接口(只是不带@FeignClient
进行注释).这段代码添加了一些自定义请求拦截器,编码器,代理等.
But, we have some existing code that uses Feign.Builder directly with Feign annotated interfaces (just not annotated with @FeignClient
). This code adds some custom request interceptors, encoder, proxy, etc.
例如:
// Feign REST interface
public interface MyService {
@RequestMapping(method = RequestMethod.GET, value = "/version")
String getVersion();
}
// Creating the builder
Feign.Builder builder = Feign.builder();
builder.requestInterceptor(new MyCustomInterceptor());
// + adding proxy, encoder, decoder, etc
// Using the builder
MyService myService = builder.target(MyService.class, "http://localhost:8080/myservice");
myService.getVersion();
我希望这个较旧的代码传播Sleuth标头.有一些简单的方法可以将其连接起来吗?
I would like this older code to propagate Sleuth headers. Is there some easy way to wire this up?
(我想一个选择是重新设计我们的Feign接口以使用@FeignClient并重新设计如何应用所有自定义拦截器,编码器等,但是最终这可能会带来很多工作,但风险很大.)
(I suppose one option is to rework our Feign interfaces to have @FeignClient and rework how all of the custom interceptors, encoders, etc get applied, but ultimately that might be a lot of work with a lot of risk.)
我是否需要做一个特殊的请求拦截器以手动注入这些请求(例如从自动连线的示踪剂)?有没有一种干净的方法(或现有的类)来做到这一点?
Do I need to do a special request interceptor to inject these manually (e.g. from an autowired Tracer)? Is there a clean way (or existing class) to do that?
推荐答案
我终于知道了.
答案几乎在这里: https://github. com/spring-cloud/spring-cloud-sleuth/issues/594
使用Feign.Builder时,其客户端需要由跟踪"实现包装.
When using Feign.Builder, its Client needs to be wrapped by a "Trace" implementation.
要做到这一点,我们只需要声明一个Client bean,然后spring/sleuth将自动处理它的包装(因为sleuth在依赖列表中).
To accomplish this, we can just declare a Client bean, then spring/sleuth will automatically take care of wrapping it (since sleuth is in the dependency list).
该声明将类似于:
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient();
}
然后,我们可以在构建客户端实现时将Client Bean传递给构建器.
Then we can just pass that Client bean to the builder when building the client implementation.
例如:
// autowiring the Client bean
@Autowired
private Client client;
// using the Client bean to build the Feign client
DemoClient demoClient = Feign.builder()
.client(client)
.target(DemoClient.class, "http://localhost:8200/demo");
这样做之后,一切似乎都正常了.我可以看到跟踪ID正在传播到远程REST服务.
After doing that, everything seemed to work. I could see the Trace Id getting propagated to the remote REST service.
这篇关于如何用Feign.Builder实现侦查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!