【问题标题】:Spring Ribbon @LoadBalanced doesn't work with @scope("prototype") for restTemplateSpring Ribbon @LoadBalanced 不适用于 restTemplate 的 @scope("prototype")
【发布时间】:2018-02-21 19:10:42
【问题描述】:

我正在关注the official spring ribbon guide,我注意到一件事。

如果以这种方式创建RestTemplate

@LoadBalanced
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  ---- I added this line
RestTemplate restTemplate(){
    logger.warn("create a restTemplate bean..."); --- added this for debug
    return new RestTemplate();
}

然后功能区客户端将无法找到服务器。 (无法用服务器 IP 地址解析客户端名称);

我调试了创建bean的过程,发现日志中出现了两次消息“create a restTemplate bean...”。

自动连接的 restTemplate 实例没有LoadBalancerInterceptor,这可能是它失败的原因。

所以我想知道是否有解决此问题的建议?

P.S: 我需要RestTemplate 做原型,这样我就可以设置不同的errorHandlers。

【问题讨论】:

    标签: spring resttemplate netflix-ribbon


    【解决方案1】:

    确实因为缺少LoadBalancerInterceptor而失败,但是可以简单地注入该类。 注入它,然后把@LoadBalanced注解去掉:

    java @Bean @Scope("prototype") RestTemplate loadBalancedTemplate(LoadBalancerInterceptor loadBalancerInterceptor) { RestTemplate template = new RestTemplate(); template.getInterceptors().add(loadBalancerInterceptor); return template; }

    【讨论】:

      【解决方案2】:

      正如author所提到的:

      事实证明,@LoadBalanced 注释不会从应用程序上下文中检索 RestTemplate bean,在“原型”范围内,它只会检索一个新实例,该实例不被任何自动装配的字段使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2015-07-20
        • 1970-01-01
        • 2018-11-21
        相关资源
        最近更新 更多