一 新建一个微服务hello-service,并修改pom.xml,增加Spring Cloud Eureka模块的依赖,具体内容如下。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
二 修改/hello请求处理接口,注入DiscoveryClient对象,在日志中打印出服务的相关内容。
public class HelloController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private DiscoveryClient client;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() throws Exception {
ServiceInstance instance = client.getLocalServiceInstance();
logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
return "Hello World";
}
}
三 在启动类上添加@EnableDiscoveryClient注解,激活Eureka中DiscoveryClient实现(自动化配置,创建DiscoveryClient接口针对Eureka客户端的EurekaDiscoveryClient实例),才能实现Controller中对服务信息的输出。
@EnableDiscoveryClient
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
四 修改配置文件,通过spring.application.name属性来为服务命名,比如命名为hello-service。再通过eureka.client.serviceUrl.defaultZone属性来指定服务注册中心地址,完整配置如下。
spring.application.name=hello-service
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
server.port=8081
五 启动hello-service服务,控制台有如下打印
2018-07-12 16:19:48.126 INFO 1776 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
2018-07-12 16:19:48.127 INFO 1776 --- [ main] c.n.e.EurekaDiscoveryClientConfiguration : Updating port to 8081
2018-07-12 16:19:48.130 INFO 1776 --- [ main] com.didispace.HelloApplication : Started HelloApplication in 9.528 seconds (JVM running for 10.455)
2018-07-12 16:19:48.185 INFO 1776 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_HELLO-SERVICE/DESKTOP-5SDKDG4:hello-service:8081 - registration status: 204
该打印说明:Tomcat启动之后,
com.netflix.discovery.DiscoveryClient对象打印了该服务的注册信息,表示服务注册成功。
六 观察服务注册中心此时打印
c.n.e.registry.AbstractInstanceRegistry : Registered instance HELLO-SERVICE/DESKTOP-5SDKDG4:hello-service:8081 with status UP (replication=false)
说明名为hello-service的服务被注册成功了。
七 观察Eureka的信息面板
八 访问http://localhost:8081/hello,直接向该服务发起请求,在控制台中可以看到如下输出。
com.didispace.web.HelloController : /hello, host:DESKTOP-5SDKDG4, service_id:hello-service
这些内容就是之前在HelloController中注入的DiscoveryClient接口对象,从服务注册中心获取的服务相关信息。