1、使用IDEA创建空项目eureka。
2、基于项目eureka创建模块eureka-server,初始化时勾选SpringCloudDiscovery中的EurekaServer或在pom中添加eurekaServer的包。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
3、在启动类中添加声明注解@EnableEurekaServer。
4、添加基本配置项。
服务端口号
server.port=8081
#服务名称
spring.application.name=eureka
#eueka注册中心地址
eureka.instance.hostname=127.0.0.1
#是否需要注册到注册中心(集群的时候需要相互注册,设置为true)
eureka.client.register-with-eureka=false
#是否需要发现服务信息(集群的时候需要相互注册,设置为true)
eureka.client.fetch-registry=false
#注册地址
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/
#本地开发时关闭自我保护机制,不可用服务及时剔除
eureka.server.enable-self-preservation=false
#本地开发时关闭自我保护机制,不可用服务及时剔除,间隔2秒钟发现服务不可用即剔除
eureka.server.eviction-interval-timer-in-ms=2000
5、启动模块,访问http://localhost:8081即可看到注册中心。
6、基于项目eureka创建模块server-a,初始化时勾选SpringCloudDiscovery中的EurekaDiscoveryClient或在pom中添加EurekaDiscoveryClient的包。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
7、启动类中添加声明注解@EnableEurekaClient。
8、添加基本配置。
#端口号
server.port=8082
#服务名称
spring.application.name=service-a
##======================eurekaBegin=====================##
#是否以ip地址进行注册
eureka.instance.prefer-ip-address=true
#是否注册
eureka.client.register-with-eureka=true
#是否需要从eureka上获取信息
eureka.client.fetch-registry=true
#注册地址
eureka.client.service-url.defaultZone=http://localhost:8081/eureka/
#心跳检测与续约时间(本地开发时将时间设置小些,保证服务关闭后注册中心及时剔除服务)
#eureka客户端向服务端发送心跳的时间间隔,单位为秒
eureka.instance.lease-renewal-interval-in-seconds=1
#eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除
eureka.instance.lease-expiration-duration-in-seconds=2
##======================eurekaEnd=====================##
9、基于项目eureka创建模块server-b,步骤同建立server-a,更改端口号即可。
10、使用idea的RunDashboard批量启动服务,访问http://localhost:8081即可看到注册中心多了两个服务。
11、在eureka-server中增加controller类添加相应的方法获取注册中心注册的服务信息。
@GetMapping("/getEurekaServiceClient")
public List<Map> getEurekaService(){
List<Application> sortedApplications = EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications();
List<Map> list = new ArrayList<>();
for (Application application : sortedApplications){
String name = application.getName();
List<InstanceInfo> instances = application.getInstances();
for (InstanceInfo instanceInfo : instances){
Map<String, Object> map = new HashMap<>();
//服务名
map.put("name", name);
//服务状态
map.put("status", instanceInfo.getStatus());
//ip地址
map.put("ip", instanceInfo.getIPAddr());
//端口
map.put("port", instanceInfo.getPort());
//实例ID
map.put("instanceId", instanceInfo.getInstanceId());
//基础请求地址
map.put("url", instanceInfo.getHomePageUrl());
list.add(map);
}
}
return list;
}