上一篇讲到了注册中心,即全部的服务提供方与服务需求方均可以注册到注册中心。服务的提供方与需求方都是单独的服务,它们是基于http restful方式通讯的,根据官网资料,springCloud各个服务方的调用方式有两种:1.Ribbon+RestTemplate;2.Feign。Ribbon是一个基于HTTP与TCP客户端的负载均衡器,Feign集成了Ribbon,当使用@FeignClient时,Ribbon会自动被调用。
1、Ribbon
1.新建一个module工程,命名:spring-cloud-producer-client-a,pom文件以下spring
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> </dependencies>
2.配置文件以下restful
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支持负载均衡。启动类以下app
@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 方法post
@RestController public class HelloControler { @Autowired TestService testService ; @RequestMapping(value = "/test") public String hello(){ return testService .hiService(); } }
7.在postman中输入http://localhost:8021/test,返回以下轮流信息rest
localhost:8029 localhost:8028
这个说明负载均衡已经起效了。
2、Feigncode