Eureka 中怎么实现服务注册与发现
Eureka 中怎么实现服务注册与发现,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
从 Spring Initializr 进行项目的初始化
访问http://start.spring.io/ 进行项目的初始化。我们将该项目命名为micro-weather-eureka-server。
更改配置
根据下面两个博客的指引来配置,加速项目的构建。
Gradle Wrapper 引用本地的发布包 : https://waylau.com/change-gradle-wrapper-distribution-url-to-local-file/
使用Maven镜像 : https://waylau.com/use-maven-mirrors/
启用 Eureka Server
为启用 Eureka Server ,在 Application 上增加@EnableEurekaServer注解即可。
@SpringBootApplication@EnableEurekaServerpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}修改项目配置
修改 application.properties,增加如下配置。
server.port: 8761eureka.instance.hostname: localhosteureka.client.registerWithEureka: falseeureka.client.fetchRegistry: falseeureka.client.serviceUrl.defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/其中:
server.port: 指明了应用启动的端口号
eureka.instance.hostname: 应用的主机名称
eureka.client.registerWithEureka: 值为
false意味着自身仅作为服务器,不作为客户端eureka.client.fetchRegistry: 值为
false意味着无需注册自身eureka.client.serviceUrl.defaultZone: 指明了应用的URL
启动 Eureka Server
启动应用,访问http://localhost:8761/,可以看到 Eureka Server 自带的 UI 管理界面。
创建 Eureka Client
我们在micro-weather-eureka-server基础上,将创建一个micro-weather-eureka-client 作为客户端,并演示如何让将自身向注册服务器进行注册,让其可以其他服务都调用。
更改配置
增加如下配置:
dependencies { //... compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') //...}一个最简单的 Eureka Client
@SpringBootApplication@EnableDiscoveryClient@RestControllerpublic class Application { @RequestMapping("/hello") public String home() { return "Hello world"; } public static void main(String[] args) { SpringApplication.run(Application.class, args); }}其中@EnableDiscoveryClient启用了服务发现的功能,只要 Eureka Client 启动了,就能被 Eureka Server 所感知。
项目配置:
spring.application.name: micro-weather-eureka-clienteureka.client.serviceUrl.defaultZone: http://localhost:8761/eureka/
运行
分别在 8081 和 8082 上启动了客户端示例。
java -jar micro-weather-eureka-client-1.0.0.jar --server.port=8081java -jar micro-weather-eureka-client-1.0.0.jar --server.port=8082
可以在 Eureka Server 上看到这两个实体的信息。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。