在第一部分中用于服务注册和查找的服务器集群已经建好, 这个部分创建一个微服务a-bootiful-client,注册在该服务器并通过名称a-bootiful-client查找和调用该服务,a-bootiful-client微服务运行三个实例,分别在端口8100, 8200, 8300, 启用Eureka Robbin load balance.
第一步:eclipse STS, File -> New -> Spring Starter Project, 添加依赖 Eureka Discovery
第二步:添加bootstrap.properties文件,并给定如下信息:
spring.application.name=a-bootiful-client
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
server.port=8200
第三步:添加@EnableDiscoveryClient, @LoadBalanced启动注册机制和负载平衡,同时定义两个路径处理Beans(/, /admin),一是为了显示服务端口信息,二是将来用于权限管理测试。
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
@RestController
class ServiceInstanceRestController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private Environment env;
@RequestMapping("/service-instances/{applicationName}")
@LoadBalanced
public List<ServiceInstance> serviceInstancesByApplicationName(
@PathVariable String applicationName) {
return this.discoveryClient.getInstances(applicationName);
}
@RequestMapping("/")
public String home() {
// This is useful for debugging
// When having multiple instance of gallery service running at different ports.
// We load balance among them, and display which instance received the request.
return "Hello from Gallery Service running at port: " + env.getProperty("local.server.port");
}
// -------- Admin Area --------
// This method should only be accessed by users with role of 'admin'
// We'll add the logic of role based auth later
@RequestMapping("/admin")
public String homeAdmin() {
return "This is the admin area of Gallery service running at port: " + env.getProperty("local.server.port");
}
}
第四步:设置环境变量,运行于三个不同端口8100, 8200, 8300 Run -> Run Configurations -> Arguments -> VM Arguments -> -Dserver.port=8300
第五步: 浏览器输入网址 http://localhost:8761/ http://localhost:8763/ 我们注意到在两个注册服务器节点上均启动了三个实例
示例代码主要参考官方Spring Cloud Eureka Sample, 本文代码:
https://github.com/china-fengguan/Spring_Cloud/tree/master/eureka-client
下一部分建立gateway,通过gateway配置对a-bootiful-client进行访问,可以观察到load balance效果,每一次访问页面会显示不同提供服务的真正端口。