祝大家每日进步,有技术问题多多交流,同时欢迎大家关注我的头条号:IT人孙会良
Spring Cloud Ribbon
一.Sping Cloud Ribbon概述
Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。
Ribbon中的核心概念是命名客户端的概念。每个负载均衡器是组合的组合的一部分,它们一起工作以根据需要联系远程服务器,并且集合具有您将其做为应用程序开发人员(例如使用@FeignClient注释)的名称。Spring Cloud使用RibbonClientConfiguration为每个命名的客户端根据需要创建一个新的集合,做为ApplicationContext。这包含(除其他外)IloadBalancer,
RestClient和ServerListFilter
Ribbon架构如下:
二. RestTemplate详解
2.1 HTTP请求的方法
(1)GET:通过请求URI得到资源
(2)POST:用于添加新的内容
(3)PUT:用于修改某个内容,若不存在则添加
(4)DELETE:删除某个内容
(5)OPTIONS :询问可以执行哪些方法
(6)HEAD :类似于GET, 但是不返回body信息,用于检查对象是否存在,以及得到对象的元数据
(7)CONNECT :用于代理进行传输,如使用SSL
(8)TRACE:用于远程诊断服务器
2.2 GET请求
对于Get请求,Spring的RestTemplate提供了许多的支持,这里仅仅列出常用的接口:
public <T> T getForObject(String url, Class<T> responseType,Object... urlVariables) throws RestClientException
public <T> T getForObject(String url, Class<T> responseType,Map<String, ?> urlVariables) throws RestClientException
public <T> T getForObject(URI url, Class<T> responseType)throws RestClientException
对于GET请求来说,我一般常用的几种形式如下:
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}",String.class,"42", "21");
或者下面这张形式:
Map<String, String> vars =Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{hotel}",String.class, vars);
以及:
Stringmessage =restTemplate.getForObject("http://localhost:8080/yongbarservice/appstore/appgoods/restTemplate?name=zhaoshijie&id=80",String.class );
2.3 POST请求
Spring的RestTemplate对post的常用接口:
public<T> T postForObject(String url, Object request, Class<T>responseType, Object... uriVariables)
throwsRestClientException
public<T> T postForObject(String url, Object request, Class<T>responseType, Map<String, ?> uriVariables)
throwsRestClientException
public<T> T postForObject(URI url, Object request, Class<T> responseType)throws RestClientException
我一般常用的方法为:
MultiValueMap<String,String> bodyMap = new LinkedMultiValueMap<String, String>();
bodyMap.setAll(urlVariables);
ResponseClassresponseClass = restTemplate.postForObject(CAR_CES_URL, bodyMap,ResponseClass.class);
以及:
HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token","e348bc22-5efa-4299-9142-529f07a18ac9");
MultiValueMap<String, String>postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("owner","11");
postParameters.add("subdomain", "aoa");
postParameters.add("comment","");
HttpEntity<MultiValueMap<String,String>> requestEntity = newHttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ParseResultVo exchange = null;
try {
exchange =restTemplate.postForObject("http://l-dnsutil1.ops.beta.cn6.qunar.com:10085/v1/cnames/tts.piao", requestEntity, ParseResultVo.class);
logger.info(exchange.toString());
} catch (RestClientException e) {
logger.info("。。。。");
}
以及:
DomainParam domainParam = new DomainParam();
domainParam.setCustomerId(1);
//...
logger.info("....");
restTe