一、服务发现Eureka Client
服务发现是基于微服务架构体系的关键原则之一,也很重要,我们可以Eureka客户端获取到注册到Eureka Server中的Eureka实例,通过实例信息来访问其对应的服务发送请求。
二、使用步骤
1.引入依赖及注解
Eureka Client的坐标依赖如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
仅仅引入一个Eureka Client依赖还是不行的,还需要引入web依赖,令工程有一个运行的环境,web的坐标依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在启动程序类上增加注解@EnableEurekaClient
2.增加配置
在正确的引入了Eureka Client依赖后启动应用,程序就会通过defaultZone
的地址,自动地注册到Eureka Server。
在yml文件中增加如下配置:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:12345/eureka/
一定要给应用起个名字,否则在Eureka注册中心显示的时候就变成了UNKNOWN
所以补加一个配置
spring:
application:
name: backend-service
这样的话看起来就正常的多了
三、实例ID
默认情况下,Eureka实例ID是按照IP:服务名:端口
的形式组成的,我们可以通过注册中心看的到,也会发现在启动日志处也有输出。
[nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_BACKEND-SERVICE/你的IP地址:backend-service:8080: registering service…
如果想要调整实例ID的组成顺序,可以增加如下配置
eureka:
instance:
instanceId: ${spring.application.name}:${spring.cloud.client.hostname}:${server.port}
我觉得默认配置就可以了,能少加就不多加。
总结
使用Eureka客户端分三步:
1、加依赖
2、补配置
3、放注解
最后,放一下全量的yml配置。
server:
port: 8080
spring:
application:
name: backend-service
eureka:
instance:
instanceId: ${spring.application.name}:${spring.cloud.client.hostname}:${server.port}
client:
serviceUrl:
defaultZone: http://localhost:12345/eureka/
补充
如果想通过代码看一下Eureka客户端实例ID长什么样子,可以执行如下代码
package com.test.backend.service.controller;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Applications;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/test")
public class UseEurekaClientController {
@Resource
private EurekaClient eurekaClient;
@GetMapping("/get")
public String getInstance() {
InstanceInfo instance = eurekaClient.getNextServerFromEureka("BACKEND-SERVICE", false);
return instance.getInstanceId();
}
}
注:启动完成之后,等一会在请求/test/get
地址,否则会报500。