注释@RibbonClient不能与 RestTemplate 一起使用



我正在尝试基于书签服务示例使用 RestTemplate 进行功能区配置,但没有运气,这是我的代码:

@SpringBootApplication
@RestController
@RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)
public class BookmarkServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookmarkServiceApplication.class, args);
    }
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/hello")
    public String hello() {
        String greeting = this.restTemplate.getForObject("http://foo/hello", String.class);
        return String.format("%s, %s!", greeting);
    }
}

错误页面如下:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Mar 22 19:59:33 GMT+08:00 2016
There was an unexpected error (type=Internal Server Error, status=500).
No instances available for foo

但是如果我@RibbonClient删除注释,一切都会好起来的,

@RibbonClient(name = "foo", configuration = SampleRibbonConfiguration.class)

下面是示例功能区配置实现:

public class SampleRibbonConfiguration {
  @Autowired
  IClientConfig ribbonClientConfig;
  @Bean
  public IPing ribbonPing(IClientConfig config) {
    return new PingUrl();
  }
  @Bean
  public IRule ribbonRule(IClientConfig config) {
    return new AvailabilityFilteringRule();
  }
}

是因为 RibbonClient 不能与 RestTemplate 一起工作吗?

另一个问题是,是否可以通过 application.yml 配置文件配置负载均衡规则等功能区配置?从功能区维基来看,似乎我们可以在属性文件中配置功能区参数,如NFLoadBalancerClassName,NFLoadBalancerRuleClassName等,Spring Cloud是否也支持此功能?

>我假设你正在使用Eureka进行服务发现。

您的特定错误:

No instances available for foo

可能由于几个原因而发生

1.) 所有服务都已关闭

foo服务的所有实例都可以合法地关闭。

解决方案:尝试访问您的尤里卡仪表板,并确保所有服务实际上都已启动。

如果您在本地运行,则尤里卡仪表板处于 http://localhost:8761/

2.) 等待心跳

当您第一次通过尤里卡注册服务时,有一段时间该服务已启动但不可用。从文档

客户端无法发现服务,直到 实例,服务器和客户端都具有相同的元数据 他们的本地缓存(因此可能需要 3 个心跳)

解决方案:在启动 foo 服务后等待 30 秒,然后再尝试通过客户端调用它。

在你的特殊情况下,我会猜测#2可能是发生在你身上的事情。您可能正在启动服务并尝试立即从客户端调用它。

当它不起作用时,您可以停止客户端,进行一些更改并重新启动。但到那时,所有检测信号都已完成,您的服务现在可用。

对于你的第二个问题。查看参考文档中的"使用属性自定义功能区客户端"部分。(链接)

最新更新