一、概述
前面通过 Eureka Client 组件创建了一个服务提供者 provider,并且在注册中心完成注册,接下来就来实现一个服务消费者 consumer,调用 provider 相关接口。
二、搭建服务消费者
先通过 Spring Boot 搭建一个微服务应用,再通过 Eureka Client 将其注册到 Eureka Server。此时的 provider 和 consumer 从代码的角度看并没有区别,都是 Eureka 客户端,我们人为地从业务角度对它们进行区分,provider 提供服务,consumer 调用服务,具体的实现需要结合 RestTemplate 来完成,即在服务消费者 consumer 中通过 RestTemplate 来调用服务提供者 provider 的相关接口。
1、创建maven 子模块consumer 。
2、pom添加 Eureka Client 依赖。
<dependencies>
<!--添加 Eureka Client 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
3、在 resources 路径下创建配置文件 application.yml,添加 Eureka Client 相关配置,此时的 Eureka Client 为服务消费者 consumer。
server:
port: 8020 #当前 Eureka Client 服务端口
spring:
application:
name: consumer #当前服务注册在 Eureka Server 上的名称
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka/ #注册中心的访问地址
instance:
prefer-ip-address: true #是否将当前服务的 IP 注册到 Eureka Server
4、创建启动springboot启动类consumerApplication 并添加RestTemplate 配置。
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
5、创建controller,注入RestTemplate 实例,业务方法通过RestTemplate 调用provider 服务。
@RequestMapping("/consumer")
@RestController
public class StudentHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll(){
return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
}
// .....完整实现参考https://gitee.com/zhengj/myspringcloud.git......
}
6、完整工程目录如下:
7、依次启动注册中心、服务提供者 provider,并运行 ConsumerApplication。
打开浏览访问注册中心界面 http://localhost:8761 可看见服务提供者和消费者已经注册到注册中心了。
8、接下来就可以访问 consumer 的相关服务了。
三、总结
使用 Eureka Client 组件在 Eureka Server 注册一个服务消费者 consumer 的具体实现,无论是服务消费者还是服务提供者,都通过 Eureka Client 组件来实现注册,实现服务消费者 consumer 之后,通过 RestTemplate 完成对服务提供者 provider 相关服务的调用。
完整demo下载地址:
https://gitee.com/zhengj/myspringcloud.git