在上一篇的文章中,讲解了服务生产者的创建,创建了Service-Producer的两个实例。SpringCloud的服务调用有两种方式,Ribbon和Feign,本篇博客讲解下Ribbon的使用。
Ribbon实现了一套客户端的负载均衡工具,它是基于HTTP和TCP实现的。
一、准备
使用上一篇博客服务生产者的创建中创建的Eureka-Server和Service-Producer。
二、创建Consumer-Ribbon
gradle依赖为
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.4.4.RELEASE'
compile('org.springframework.cloud:spring-cloud-starter-ribbon:1.4.4.RELEASE')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
添加@EnableDiscoveryClient注解,同时配置RestTemplate类的注入,添加 @LoadBalanced注解,进行负载均衡。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerRibbonApplication
{
public static void main(String[] args) {
SpringApplication.run(ConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
添加测试Controller,对于RestTemplate的使用,我们的第一个url参数有一些特别。这里请求的host位置并没有使用一个具体的IP地址和端口的形式,而是采用了服务名的方式组成。那么这样的请求为什么可以调用成功呢?因为Spring Cloud Ribbon有一个拦截器,它能够在这里进行实际调用的时候,自动的去选取服务实例,并将实际要请求的IP地址和端口替换这里的服务名,从而完成服务接口的调用。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Created by wzj on 2018/5/19.
*/
@RestController
public class ConsumerController
{
/**
* 注入
*/
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/consumer")
public String client()
{
return restTemplate.getForObject("http://service-producer/client",String.class);
}
}
三、测试
同时启动Service-Producer-A、Service-Producer-B和Consumer-Ribbon
浏览器访问http://127.0.0.1:10006/consumer,结果负载到了Service-Producer-A
关闭Service-Producer-A服务,再次访问http://127.0.0.1:10006/consumer,发现负载到了Service-Producer-B
源码Github地址:https://github.com/HelloKittyNII/SpringCloud/tree/master/SpringCloudFramework