【发布时间】:2021-10-26 10:33:03
【问题描述】:
我想尝试使用 2.5.4 spring boot 的微服务并在发现中遇到问题
步骤:
使用 @LoadBalanced 创建了一个 RestTemplate,并尝试使用“url 中的应用程序名称”调用服务
我在属性中有注册和获取注册真实(认为这应该得到可用的服务?)
错误:没有这样的主机是已知的
我在努力
@Autowired
private DiscoveryClient discoveryClient;
然后做
discoveryClient.getInstances("myappservice-name").forEach((ServiceInstance s) -> {
System.out.println(ToStringBuilder.reflectionToString(s));
});
但是所有示例都告诉使用端点?或 commandLineRunner。我都在寻找自动加载
https://spring.io/guides/gs/service-registration-and-discovery/
不能为每个应用调用下面的代码
@RequestMapping("/service-instances/{applicationName}") public
List<ServiceInstance> serviceInstancesByApplicationName(
如何自动注册?
编辑:更详细的问题
(1) 服务应用程序
bootstrap - spring.application.name=pluralsight-toll-service
应用道具
server.port=0
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.instance.instance-id=${spring.application.name}:${random.int}
eureka.instance.hostname=localhost
management.endpoints.web.exposure.include=*
应用程序
@SpringBootApplication
@EnableEurekaClient
public class PluralsightEurekaTollrateServiceApplication {
我看到应用在 eureka 服务器中注册了
(2) 客户端 引导
spring.application.name=pluralsight-tollrate-billboard
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
application.props
server.port=8081
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
management.endpoints.web.exposure.include=*
应用程序
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PluralsightEurekaTollrateBillboardApplication {
控制器
@LoadBalanced
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Autowired
RestTemplate restTemplate;
@RequestMapping("/dashboard")
public String GetTollRate(@RequestParam int stationId, Model m) {
TollRate tr = restTemplate.getForObject("http://pluralsight-toll-service/tollrate/" + stationId, TollRate.class);
错误:pluralsight-toll-service 主机未知
如何使用名称从客户端调用服务
【问题讨论】:
-
可以通过在 Application 类上添加 @EnableDiscoveryClient 并在属性中配置注册表 url 和端口来完成对注册表的注册。我注意到这就是你所要求的。如果您想做更多的事情,请您详细说明一下吗?
-
我尝试了您的建议,但没有奏效。我将编辑问题
-
好的,我想我知道你现在需要做什么了。那为什么不使用 feignclient 呢?它支持开箱即用的服务发现
-
我明白你的意思,但我想解决这个问题。我怎么知道,如果我的客户知道服务等。
-
该用例应该可以工作。事实上,我们有一个可以做到这一点的工作示例:github.com/spring-cloud-samples/spring-cloud-intro-demo/blob/…。项目设置可能存在问题 - 如果您通过 GitHub 链接共享它,我可以为您查看。
标签: spring-boot spring-cloud netflix-eureka