上一篇讲到了注册中心,即所有的服务提供方与服务需求方都可以注册到注册中心。服务的提供方与需求方都是单独的服务,它们是基于http restful方式通信的,根据官网资料,springCloud各个服务方的调用方式有两种:1.Ribbon+RestTemplate;2.Feign。Ribbon是一个基于HTTP与TCP客户端的负载均衡器,Feign集成了Ribbon,当使用@FeignClient时,Ribbon会自动被调用。
一、Ribbon 1.新建一个module工程,命名:spring-cloud-producer-client-a,pom文件如下org.springframework.cloud spring-cloud-starter-ribbon
2.配置文件如下
spring.application.name=spring-cloud-producer-client-aserver.port=8021eureka.client.serviceUrl.defaultZone=http://localhost:8026/eureka/
3.在本工程启动类中,通过@EnableDiscoveryClient这个注解表示将该工程注册到注册中心,同时向IOC注入一个bean,并采用@LoadBalanced这个注解表明注册的bean支持负载均衡。启动类如下
@SpringBootApplication@EnableDiscoveryClientpublic class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run(ServiceRibbonApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }}
4.假设我们已经有两个服务提供方(producer-hello)已经注册到注册中心,假设这两个服务提供方工程一模一样,只是端口不一样(8029与8028),这时我们会发现,producer-hello在注册中心注册了两个实例,它们相当于一个集群。且producer-hello服务提供一个对外的接口/resultSelf,返回服务自己的ip+端口。
5.接着第3步,我们写一个TestService,并通过restTemplate这个bean来消费producer-hello提供的接口/resultSelf,代码如下:@Servicepublic class TestService { @Autowired RestTemplate restTemplate; public String hiService() { return restTemplate.getForObject("http://producer-hello/resultSelf,String.class); }}
6.来一个Controller,其调用TestService 方法
@RestControllerpublic class HelloControler { @Autowired TestService testService ; @RequestMapping(value = "/test") public String hello(){ return testService .hiService(); }}
7.在postman中输入
localhost:8029localhost:8028
这个说明负载均衡已经起效了。
二、Feign