上一篇讲到了注册中心,即所有的服务提供方与服务需求方都可以注册到注册中心。服务的提供方与需求方都是单独的服务,它们是基于http restful方式通信的,根据官网资料,springCloud各个服务方的调用方式有两种:1.Ribbon+RestTemplate;2.Feign。Ribbon是一个基于HTTP与TCP客户端的负载均衡器,Feign集成了Ribbon,当使用@FeignClient时,Ribbon会自动被调用。
一、Ribbon
1.新建一个module工程,命名:spring-cloud-producer-client-a,pom文件如下
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
</dependencies>
2.配置文件如下
spring.application.name=spring-cloud-producer-client-a
server.port=8021
eureka.client.serviceUrl.defaultZone=http://localhost:8026/eureka/
3.在本工程启动类中,通过@EnableDiscoveryClient这个注解表示将该工程注册到注册中心,同时向IOC注入一个bean,并采用@LoadBalanced这个注解表明注册的bean支持负载均衡。启动类如下
@SpringBootApplication
@EnableDiscoveryClient
public 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,代码如下:
@Service
public class TestService {
@Autowired
RestTemplate restTemplate;
public String hiService() {
return restTemplate.getForObject("http://producer-hello/resultSelf,String.class);
}
}
6.来一个Controller,其调用TestService 方法
@RestController
public class HelloControler {
@Autowired
TestService testService ;
@RequestMapping(value = "/test")
public String hello(){
return testService .hiService();
}
}
7.在postman中输入http://localhost:8021/test,返回如下轮流信息
localhost:8029
localhost:8028
这个说明负载均衡已经起效了。
二、Feign