Spring Cloud服务发现组件Eureka
source link: https://www.pkslow.com/archives/spring-cloud-eureka
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Netflix Eureka是微服务系统中最常用的服务发现组件之一,非常简单易用。当客户端注册到Eureka后,客户端可以知道彼此的hostname和端口等,这样就可以建立连接,不需要配置。
Eureka 服务端
添加Maven依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
添加注解@EnableEurekaServer
到Spring Boot的启动类中:
package com.pkslow.cloud.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServer {
public static void main(String[] args) {
SpringApplication.run(EurekaServer.class, args);
}
}
配置端口号:
server:
port: 8761
eureka:
client:
fetch-registry: false
register-with-eureka: false
然后启动服务,在浏览器中打开: http://localhost:8761/
我们就可以看到服务端的信息了,但目前还没客户端注册。
Eureka客户端
只有注册到Eureka服务端的服务,才能被其它服务发现。
添加依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
添加注解@EnableEurekaClient
:
package com.pkslow.cloud.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class RestService {
public static void main(String[] args) {
SpringApplication.run(RestService.class, args);
}
}
把服务端的地址配置好:
spring.application.name=rest-service
server.port=8081
pkslow.admin=larry|18|[email protected]
eureka.client.service-url.defaultZone: http://localhost:8761/eureka
eureka.instance.prefer-ip-address=true
management.endpoints.web.exposure.include=*
注意这个spring.application.name
是很关键的,以它为名字注册到Eureka。
启动该服务,并刷新Eureka服务端的页面:
就可以看到有服务注册上来了。
代码请看GitHub: https://github.com/LarryDpk/pkslow-samples
References:
Introduction to Spring Cloud Netflix Eureka
Code for all: GitHub
欢迎关注微信公众号<南瓜慢说>,将持续为你更新...
Recommendations:
Cloud Native
Terraform
Container: Docker/Kubernetes
Spring Boot / Spring Cloud
Https
如何制定切实可行的计划并好好执行
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK