客戶端負載均衡:Spring Cloud Ribbon

Spring Cloud Ribbon是一個基于HTTP和TCP的客戶端負載均衡工具,它基于Netflix Ribbon實現(xiàn)。

客戶端負載均衡

負載均衡指的是服務端負載均衡,分為硬件負載均衡和軟件負載均衡。硬件負載均衡指的是通過在服務器節(jié)點之間安裝專門用于負載均衡的設備。而軟件均衡指的是通過在服務器上安裝一些具有均衡負載功能或者模塊的軟件來實現(xiàn)請求分發(fā)工作,比如nginx等。
通過Spring Cloud Ribbon的封裝,我們在微服務架構中使用客戶端負載均衡調(diào)用非常簡單,只需要兩步:
-服務提供者只需要啟動多個服務實例并注冊到一個注冊中心或是多個相關聯(lián)的服務注冊中心
-服務消費者直接通過調(diào)用被@LoadBalanced注解修飾過的RestTemplate來實現(xiàn)面向服務的接口調(diào)用。
這樣,我們就可以將服務提供者的高可用以及服務消費者的負載均衡調(diào)用一起實現(xiàn)了

RestTemplate

GET請求

第一種:getForEntity函數(shù)。該方法返回的是ResponseEntity,該對象是Spring對HTTP請求響應的封裝。比如下面的例子,訪問USER-SERVER服務的/user請求,同時最后一個參數(shù)didi會替換url中的{1}占位符,而返回的ResponseEntity對象的body內(nèi)容類型會根據(jù)第二個參數(shù)轉換為String類型。

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://USER_SERVICE/user?name={1}", String.class, "didi");
String body = responseEntity.getBody();

如果希望返回的是User對象類型,可以這樣實現(xiàn):

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://USER_SERVICE/user?name={1}", User.class, "didi");
User body = responseEntity.getBody();

第二種:getForObject函數(shù)。該方法可以理解為getForEntity的進一步封裝,它通過HttpMessageConverterExtractor對HTTP的請求響應體body內(nèi)容進行對象轉換,實現(xiàn)請求直接返回包裝好的對象內(nèi)容:

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class)

當不需要關注請求響應除了body外的其他內(nèi)容時,該函數(shù)就非常好用,可以少一個從Response中獲取body的步驟

POST請求

在RestTemplate中,對POST請求時可以通過以下三種方法進行調(diào)用實現(xiàn)。
第一種:postForEntity函數(shù),該方法同GET請求中的getForEntity類似,會在調(diào)用后返回ResponseEntity<T>對象,其中T為請求響應的body類型。

RestTemplate restTemplate = new RestTemplate();
User user = new User("didi", 30);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://USER_SERVER/user", user, String.class);
String body = responseEntity.getBody();

第二種:postForObject函數(shù),該方法也與getForObject相似,作用是簡化postForEntity的后續(xù)處理

RestTemplate restTemplate = new RestTemplate();
User user = new User("didi", 20);
String postResult = restTempla 七 e.postForObjec 七 ("http: //USER-SERVICE/user", user,String.class);

第三種:postForLocation函數(shù)。該方法實現(xiàn)了以POST請求提交資源,并返回新資源的URI。

User user = new User("didi", 30);
URI responseURI = restTemplate.postLocation("http://USER-SERVICE/user", user);

PUT請求

在RestTemplate中,對PUT請求可以通過put方法進行調(diào)用實現(xiàn)。

RestTemplate restTemplate = new RestTemplate();
Long id = 1000L;
User user = new User("didi", 10);
restTemplate.put("http://USER-SERVICE/user/{1}", user, id);

DELETE請求

在RestTemplate中,對DELETE請求可以通過delete方法進行調(diào)用實現(xiàn)。

RestTemplate restTemplate = new Res 七 Template();
Long id= 10001L;
restTemplate.delete("http://USER-SERVICE/user/{1)", id);

負載均衡器

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容