注:参考卓永超《Spring Cloud 微服务实践》
spring boot 版本为1.3.7
1、pom 文件中添加必要依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
2、编写测试服务
@RestController
public class HelloController {
private Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("hello")
public String hello() {
ServiceInstance si = discoveryClient.getLocalServiceInstance();
logger.info("hello,host" + si.getHost() + ",service_id " + si.getServiceId());
return "hello world";
}
}
3、使用@EnableDiscoveryClient ,激活Eureka中对DiscoveryClient 的实现
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
//SpringApplication.run(EurekaClientApplication.class, args);
new SpringApplicationBuilder(EurekaClientApplication.class).web(true).run(args);
}
}
4、在application.properties 文件中指定服务名称和注册中心地址
spring.application.name=hello-server
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
5、观察启动服务客户端服务之后 , 观察注册中心console 打印出如下信息
Registered instance HELLO-SERVER/zhlm-PC:hello-server with status UP (replication=false)
或访问http://localhost:8080/hello 服务客户端控制台打印出如下信息
hello,hostzhlm-PC,service_id hello-server
或在注册中心首页观察到
表示注册中心客户端搭建成功