一、简介
-
Eureka作为SpringCloud的五大组件之一,主要用于服务的注册与发现,作为服务的注册中心。Eureka服务器没有后端存储,但是注册表中的所有服务实例都必须发送心跳信号以使其注册保持最新(因此可以在内存中完成)。客户端还具有Eureka注册的内存缓存(因此,对于每个对服务的请求,它们都不必转到注册表)。
二、Eureka服务端
-
pom配置
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <!-- 安全验证 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
-
配置文件
eureka: instance: # 实例名,可通过配置host文件 hostname: discovery client: # Eureka服务端本身也是一个客户端,可通过注册中心的心跳机制+内存缓存来对故障服务恢复。如果Eureka是单节点模式,则需要设置为 #false,否则会一直报错注册服务失败。如果是集群配置,我们需要添加多个实例的注册配置 #自动拉去服务 fetch-registry: false # 是否自动注册服务 默认为true register-with-eureka: false serviceUrl: defaultZone: http://bike:bike123@${eureka.instance.hostname}:${server.port}/eureka/ #关闭自我保护机制,保证不可用服务及时踢出 server: enable-self-preservation: false # 开启服务注册密码验证 spring: security: user: name: **** password: ****
-
启动配置
@SpringBootApplication @EnableEurekaServer//开启服务注解 public class BikeEurekaApplication { public static void main(String[] args) { SpringApplication.run(BikeEurekaApplication.class, args); } /** * 当Spring Security在类路径上时, * 它将要求在每次向应用程序发送请求时都发送有效的CSRF令牌。 * Eureka客户通常不会拥有有效的跨站点请求伪造(CSRF)令牌,您需要为/eureka/**端点禁用此要求。 */ @EnableWebSecurity class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().ignoringAntMatchers("/eureka/**"); super.configure(http); } } }
-
测试验证
启动项目,访问http://server-ip:port/ 即可看到注册中心管理界面,输入默认配置的用户名密码即可
三、Eureka客户端
-
pom配置
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
-
配置文件
eureka: client: register-with-eureka: true fetch-registry: true #开启健康检查,默认情况下,Eureka使用客户端心跳来确定客户端是否启动,默认持续时间为30秒 #直到实例,服务器和客户端在其本地缓存中都具有相同的元数据后,客户端才能发现该服务(因此可能需要3个心跳) #可以通过设置eureka.instance.leaseRenewalIntervalInSeconds来更改周期 healthcheck: enabled: true #Eureka客户端属性可以更改和刷新。发生刷新时,客户端将从Eureka服务器中注销, #并且可能会在短暂的时间内不提供给定服务的所有实例。消除这种情况的一种方法是禁用刷新Eureka客户端的功能 refresh: enable: false serviceUrl: #discovery 由于开启了用户密码验证,注册时需设置用户名密码username:password@格式 defaultZone: http://bike:bike123@127.0.0.1:8120/eureka/ instance: hostname: gateway prefer-ip-address: true #Eureka实例注册的ID等于其主机名(即,每个主机仅提供一项服务)实例id instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port} # springboot2.0以后新增/actuator根路径,如果使用了非默认上下文路径,这里配置也需要更改 #例如:${server.servletPath}/actuator/info statusPageUrlPath: /actuator/info healthCheckUrlPath: /actuator/health #元数据配置。信息的标准元数据,例如主机名,IP地址,端口号,状态页和运行状况检查。这些都发布在服务注册表中,并由客户端用于以直接方式联系服务 #如果还有其他元数据需要在实例中注册,则可通过设置这个参数,并且可以在远程客户端访问此元数据 # metadata-map:
-
启动配置
@SpringBootApplication @EnableEurekaClient//开启客户端注解 public class BikeGatewayApplication { public static void main(String[] args) { SpringApplication.run(BikeGatewayApplication.class, args); } }
-
测试验证
先启动eureka服务器,再启动eureka客户端,通过注册中心管理界面可以看到服务已经注册到注册中心了。
中文地址:中文地址
源码地址:源码