Spring Cloud Ribbon是一個基於HTTP和TCP的客戶端負載均衡工具,它基於Netflix Ribbon實現。經過Spring Cloud的封裝,可讓咱們輕鬆地將面向服務的REST模版請求自動轉換成客戶端負載均衡的服務調用。Spring Cloud Ribbon雖然只是一個工具類框架,它不像服務註冊中心、配置中心、API網關那樣須要獨立部署,可是它幾乎存在於每個Spring Cloud構建的微服務和基礎設施中。由於微服務間的調用,API網關的請求轉發等內容,實際上都是經過Ribbon來實現的,包括後續將要介紹的Feign,它也是基於Ribbon實現的工具。因此,對Spring Cloud Ribbon的理解和使用,對於咱們使用Spring Cloud來構建微服務很是重要。ribbon是一個負載均衡客戶端,能夠很好的控制htt和tcp的一些行爲。Feign默認集成了ribbon。java
啓動eureka服務,並啓動兩個Client,能夠看到兩SERVICE-HI個服務都註冊到erueka上git
新建項目spring boot ,pom文件github
<properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR2</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
修改配置web
eureka.client.serviceUrl.defaultZone=http://地址/eureka/ server.port: 1003 spring.application.name: service-ribbon
在main入口處添加@EnableDiscoveryClient 、@EnableEurekaClient註解,經過@EnableDiscoveryClient向註冊中心註冊服務,而且向程序的ioc注入一個bean: restTemplate;並經過@LoadBalanced註解代表這個restRemplate開啓負載均衡的功能spring
@EnableDiscoveryClient @EnableEurekaClient @SpringBootApplication public class ServiceribbonApplication { public static void main(String[] args) { SpringApplication.run(ServiceribbonApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate(){ return new RestTemplate(); } }
新建一個service類,經過以前注入ioc容器的restTemplate來消費service-hi服務的「/hello」接口,在這裏咱們直接用的程序名替代了具體的url地址,在ribbon中它會根據服務名來選擇具體的服務實例,根據服務實例在請求的時候會用具體的url替換掉服務名瀏覽器
@Service public class HelloService { @Autowired RestTemplate restTemplate; public String hiService(String name) { return restTemplate.getForObject("http://SERVICE-HI/hello/hi?name="+name,String.class); } }
新建一個controller去調用serivceapp
@RestController @RequestMapping("hello") public class HelloControler { @Autowired HelloService helloService; @GetMapping(value = "/hi") public String hi(@RequestParam String name) { String a=helloService.hiService( name ); return a; } }
啓動項目在瀏覽器上刷連接訪問http://localhost:1003/hello/hi?name=aa 會交換出現,能夠看到port分別對應兩個不一樣端口的服務負載均衡
hi aa ,i am from port:1002 hi aa ,i am from port:1001
這說明當咱們經過調用restTemplate.getForObject("http://SERVICE-HI/hello/hi?name="+name,String.class)方法時,已經作了負載均衡,訪問了不一樣的端口的服務實例。框架