Ribbon
Ribbon是一個基於HTTP和TCP客戶端的負載均衡器。Feign中也使用Ribbon.
Ribbon可以在通過客戶端中配置的ribbonServerList服務端列表去輪詢訪問以達到均衡負載的作用。
當Ribbon與Eureka聯合使用時,ribbonServerList會被DiscoveryEnabledNIWSServerList重寫,擴展成從Eureka注冊中心中獲取服務端列表。同時它也會用NIWSDiscoveryPing來取代IPing,它將職責委托給Eureka來確定服務端是否已經啟動。
pom.xml依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
在應用主類中,通過@EnableDiscoveryClient
注解來添加發現服務能力。創建RestTemplate實例,並通過@LoadBalanced
注解開啟均衡負載能力。
@SpringBootApplication @EnableDiscoveryClient //發現服務的能力
public class RibbonApplication { //rest 請求對象,具有負載均衡的能力
@Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(RibbonApplication.class, args); } }
創建ConsumerController
來消費COMPUTE-SERVICE
的add服務。通過直接RestTemplate來調用服務,計算10 + 20的值。
@RestController public class ConsumerController { @Autowired RestTemplate restTemplate; @RequestMapping(value = "/add", method = RequestMethod.GET) public String add() {
//調用服務 return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody(); } }
application.properties
中配置eureka服務注冊中心。
Ribbon總結:
- 第一步先選擇 Eureka Server, 它優先選擇在同一個Zone且負載較少的Server;
- 第二步再根據用戶指定的策略,在從Server取到的服務注冊列表中選擇一個地址。其中Ribbon提供了三種策略:輪詢、斷路器和根據響應時間加權。
Feign
Feign是一個聲明式的Web Service客戶端,它使得編寫Web Serivce客戶端變得更加簡單。我們只需要使用Feign來創建一個接口並用注解來配置它既可完成。它具備可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的編碼器和解碼器。Spring Cloud為Feign增加了對Spring MVC注解的支持,還整合了Ribbon和Eureka來提供均衡負載的HTTP客戶端實現。
在應用主類中通過@EnableFeignClients
注解開啟Feign功能
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients //開啟feign public class FeignApplication { public static void main(String[] args) { SpringApplication.run(FeignApplication.class, args); } }
定義compute-servic
e服務的接口
@FeignClient("compute-service") public interface ComputeClient { @RequestMapping(method = RequestMethod.GET, value = "/add") Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b); }
- 使用
@FeignClient("compute-service")
注解來綁定該接口對應compute-service服務 - 通過Spring MVC的注解來配置compute-service服務下的具體實現,注意:定義的url 必須與提供服務的url一致,包括請求方式、參數名
在web層中調用上面定義的ComputeClient
@RestController public class ConsumerController {
@Autowired ComputeClient computeClient;//feign 的代理類
@RequestMapping(value = "/add", method = RequestMethod.GET) public Integer add() {
//調用遠程服務方法 return computeClient.add(10, 20); } }
application.properties
中配置eureka服務注冊中心。
Feign總結:
- 我們使用Feign提供的注解編寫HTTP接口的客戶端代碼非常簡單, 只需要聲明一個Java接口加上少量注解即可完成。
- Feign會幫我們處理好一切. 根據我們的接口聲明, Feign會在Spring容器啟動之后, 將生成的代理類注入, 所以我們不需要寫HTTP調用的實現代碼就能完成REST接口的調用.
- Feign服務客戶端 定義的請求url必須與服務提供者url一致。
- Feign服務客戶端中的接口名、返回對象可以任意定義。但對象中的屬性類型和屬性名必須一致,與兩個對象中的屬性順序和數量無關
- 啟動 Eureka注冊中心、服務提供者、Feign服務客戶端,然后 Eureka注冊中心掛掉時,Feign服務客戶端消費服務是不受影響的。