SpringCloud 之 Eureka

一、先来搭建一个 Eureka Server 作为注册中心
1.引入依赖
<!--添加eureka服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2.写配置
作为注册中心,端口号是 8001,服务名用的 service-eureka

#配置端口号
server:
port: 8001

#服务名
spring:
application:
name: service-eureka
这个 eureka 配置目的就是把服务添加到注册中心去
注册的地址是:http://localhost:8001/eureka/

#eureka配置
eureka:
client:
# 不把服务注册到注册中心
# register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8001/eureka/
server:
#主动失效时间
eviction-interval-timer-in-ms: 30000
registry-sync-retry-wait-ms: 500
a-s-g-cache-expiry-timeout-ms: 60000
peer-eureka-nodes-update-interval-ms: 15000
renewal-threshold-update-interval-ms: 300000
#测试环境关闭自我保护模式
# enable-self-preservation: false
3.启动器添加注解
添加 @EnableEurekaServer 启动注册中心
由于作为注册中心没有数据库这些玩意,所以启动报错了 @SpringBootApplication 后面添加
exclude= {DataSourceAutoConfiguration.class} 

@EnableEurekaServer
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
4.启动并访问注册中心
访问路径:localhost:8001


这里可以看到 service-eureka 作为一个服务注册到注册中心里了

二、写一个服务作为 Eureka 的客户端注册到注册中心
1.引入依赖
<!--添加eureka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.写配置
微服务的端口号是 8084,服务名用的 service-admin

#配置端口号
server:
port: 8084

#服务名
spring:
application:
name: service-admin
依然把服务添加到注册中心去
注册的地址依然是:http://localhost:8001/eureka/

#eureka配置
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
#间隔多少秒去服务端拉去注册信息
registry-fetch-interval-seconds: 10
instance:
#发送心跳给server端频率
lease-renewal-interval-in-seconds: 30
#健康检查地址
health-check-url-path: /actuator/health
prefer-ip-address: true
3.启动器添加注解
@EnableEurekaClient 注解是基于spring-cloud-netflix依赖,只能eureka使用
@EnableDiscoveryClient 注解是基于spring-cloud-commons依赖,并且在classpath中实现
它们的作用是一样的,所以我选择 @EnableDiscoveryClient
添加 @EnableDiscoveryClient 将服务作为客户端注册到注册中心

@EnableDiscoveryClient
@SpringBootApplication
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
4.启动并访问注册中心
访问路径:localhost:8001
---------------------

猜你喜欢

转载自www.cnblogs.com/hyhy904/p/11106088.html
今日推荐