



接下来尝试一个Eureka的示例。
新建一个Maven项目,在pom.xml中添加对Eureka服务端的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
新建EurekaServerApplication.java,添加@EnableEurekaServer注解:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
启动程序后,打开 http://localhost:8080/ 就可以看到如图2-2所示的监控页面,图中展示了向Eureka注册的所有客户端。
图2-2 服务注册Eureka的监控显示结果
启动一个服务提供方并注册到Eureka。新建一个项目并在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
新建EurekaProviderApplication.java,并对外暴露一个sayHello的HTTP接口。
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaProviderApplication {
@RequestMapping("/sayHello")
public String sayHello(String name){
return "hello "+name;
}
public static void main(String[] args) {
new SpringApplicationBuilder(EurekaProviderApplication.class).web(true).run(args);
}
}
在application.yml配置Eureka服务端地址以及自身服务名称:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ #在注册中心配置Eureka地址
spring:
application:
name: myprovider #自身名字
启动EurekaProviderApplication后,再去看Eureka的监控页面,应该能看到如图2-3所示信息,表明服务已经注册到Eureka。
图2-3 在Eureka上注册成功
注意
还有一种方法就是直接使用原生的com.netflix.discovery.EurekaClient(对应Spring Cloud的DiscoveryClient)。通常,尽量不要直接使用原始的Netflix的Eureka Client,因为Spring已经对其进行封装抽象,应尽可能使用DiscoveryClient。
一旦在应用中使用了@EnableDiscoveryClient或者@EnableEurekaClient,就可以从Eureka Server中使用服务发现功能。
利用如下代码,通过DiscoveryClient可以从Eureka服务端获得所有提供myprovider服务的实例列表,并根据获得的ServiceInstance对象获取每个提供方的相关信息,如端口IP等,从中选取第一个提供方,通过Spring的RestTemplate发起HTTP请求进行调用。对于获取到的提供方集合,我们根据什么规则去选取哪个提供方?能否做到负载均衡呢?这将在第5章详细介绍。
@SpringBootApplication
@EnableDiscoveryClient
@Slf4j
@RestController
public class EurekaClientApplication {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
@Autowired
private DiscoveryClient client;
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/sayHello" ,method = RequestMethod.GET)
public String sayHello(String name) {
List<ServiceInstance> instances = client.getInstances("myprovider");
if (!instances.isEmpty()) {
ServiceInstance instance = instances.get(0);
log.info(instance.getUri().toString());
String result=restTemplate.getForObject(instance.getUri().toString()+ "/sayHello?name="+name,String.class);
return result;
}
return "failed";
}
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
此时,我们通过HTTP请求调用/sayHello接口,则可以看到服务调用方从Eureka获取服务提供方信息,并进行调用的日志信息了。
提示
不要在@PostConstruct方法以及@Scheduled中(或者任何ApplicationContext还没初始完成的地方)使用EurekaClient。其需要等待SmartLifecycle(phase=0)初始化完成才可以。