我的微服务应用程序基于spring-cloud
:zuul
网关配置在两个微服务之前:service-a和service-b。
我的一个API要求service-a请求service-b;我使用feign
。
Zuul将X-FORWARDED-*
头发送到服务,以便他们正确地重写HATEOAS链接(当服务配置为ForwardedHeaderFilter
时)。
我的问题是服务使用Feign
相互通信,Hystrix
依赖于Hystrix
。 RequestContextHolder
为每个请求创建一个新线程(我们不使用SEMAPHORE配置),因此Spring的feign
中的请求在从service-a到service-b的Feign请求中丢失,我无法用feign
请求丰富自原始请求丢失以来,hystrix.shareSecurityContext: true
拦截器已经停止。
现在Spring直接支持转发授权令牌,参数为implement my own HystrixConcurrencyStrategy
没有任何“开箱即用”的配置让Hystrix在线程之间共享请求。
一个解决方案可以是Pull Request,这是netflix.hystrix的一个类。我的最新发现是这个@Bean
public RequestAttributeHystrixConcurrencyStrategy hystrixRequestAutoConfiguration() {
return new RequestAttributeHystrixConcurrencyStrategy();
}
已被发送到spring-cloud-netflix,但遗憾的是没有集成。
我可以尝试复制Pull请求的代码,并创建一个bean,就像“eacdy”写的那样:
Zuul
有没有更简单的解决方案来转发Hystrix
与Zuul
的标头?
我想当我使用Hystrix
,HATEOAS
和X-FORWARDED-*
微服务相互沟通时,我想要做的是非常标准的,所以也许已经存在某些东西(我找不到)?
谢谢 !
我认为这是很常见的事情,但经过大量的研究,我找不到用Feign
和Hystrix
自动转发Feign
标头的方法。
所以,我寻找另一个解决方案,它的工作原理非常干净:
X-Forwarded-*
客户端中,我声明了一个特定的配置“ServiceBFeignConfig”,除了转发令牌之外,还添加了与网关对应的@Configuration
public class ServiceBFeignConfig {
@Autowired
private ApplicationProperties applicationProperties;
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
OAuth2AuthenticationDetails details =
(OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
if (applicationProperties.getFeign().getGatewayEnabled()) {
requestTemplate.header("X-Forwarded-Host", applicationProperties.getFeign().getGatewayHost());
requestTemplate.header("X-Forwarded-Port", applicationProperties.getFeign().getGatewayPort());
requestTemplate.header("X-Forwarded-Proto", applicationProperties.getFeign().getGatewayProtocol());
requestTemplate.header("X-Forwarded-Prefix", applicationProperties.getFeign().getServiceBPrefix());
}
}
};
}
}
头:Spring Cloud Config
您可以看到网关主机和端口是在属性文件中配置的(在我的例子中由@Configuration
提供)。 service-b前缀也在这些文件中设置。
仅当在属性文件中设置“gatewayEnabled”属性时,才会添加这些标头。
@ComponentScan(basePackages = { "com.myservice" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.myservice.ignorescan.*"))
注释,因此将其放在“ignorescan”包中,并在您的主Spring引导类上,使用:qazxswpoi
最后,如果您将gatewayEnabled设置为true,则会添加Forward标头,并且对网关的API调用将获得正确的HATEOAS链接。