在pom.xml中引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
添加注解@EnableDiscoveryClient
编写测试类
import java.util.List;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private static final Logger LOGGER = Logger.getLogger(HelloController.class);
@Autowired
private Registration registration; // 服务注册
@Autowired
private DiscoveryClient discoveryClient; // 服务发现客户端
@RequestMapping("/provider")
public String provider() {
ServiceInstance instance = serviceInstance();
String infoString = "provider service, host = " + instance.getHost()
+ ", service_id = " + instance.getServiceId();
LOGGER.info(infoString);
return infoString;
}
/**
* 获取当前服务的服务实例
*
* @return ServiceInstance
*/
public ServiceInstance serviceInstance() {
List<ServiceInstance> list = discoveryClient.getInstances(registration.getServiceId());
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}
配置application.properties
spring.application.name=hello-server
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
启动上一篇的注册中心。再启动服务提供者
访问localhost:1111