java村支书 · 2019年11月08日

常用的RPC架构系列---http client和RestTemplate

HTTP Client

超文本传输协议(http)应该可以说是现在互联网上使用最多最重要的协议了,http协议不仅仅能使我们浏览器上网,还广泛应用在各个系统之间的通信,WebService就是基于http协议进行传输的一种协议。

JDK自带的java.net包下提供了基于HTTP协议的api,但是这个功能并没有完善,因此在实际项目中,还是使用第三方组件apache下的httpclient。新的HttpComponents分别HttpClient和HttpCore两个模块。其中HttpClient提供了面向用户的API,而HttpCore提供了比较底层的API。我们使用HttpClient就能满足我们的需求,而且HttpClient使用起来简单,方便。

http client使用步骤

在使用之前,先创建服务提供方的代码:

    @GetMapping(value="/sayHello2")
    public String sayHello2(String username){
        return "你好,"+ username;
    }

使用httpClient大致分为五个步骤:

要使用Http Client,先引入依赖:

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

1,构建httpclient对象

CloseableHttpClient httpClientDefault = HttpClients.createDefault();

2,构建uri对象

    //http://localhost:8081/sayHello?username=李四
    URI uri = new URIBuilder().setScheme("http")
                              .setHost("localhost")
                              .setPort(8081)
                              .setPath("/sayHello2")
                              .addParameter("username", "李四")
                              .build();

3,构建请求对象

HttpClient支持http/1.1规范中定义的get,head,post,put,delete,trace,options。httpClient为其提供了对应的对象HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace,HttpOptions。我们使用最多的也就是HttpGet和HttpPost。

    HttpGet httpGet = new HttpGet();
    httpGet.setURI(uri);

4,发送请求

    String returnString = httpClientDefault.execute(httpGet, new ResponseHandler<String>() {
        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            String toString = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("utf-8"));

            return toString;
        }
    });

5,获取请求结果

    System.out.println("返回信息:");
    System.out.println(JSON.toJSONString(returnString));

file

以上步骤是不是很繁琐?当然,HttpClient还提供了流式API更加方便,简单创建http请求

HttpClient流式API

引入支持流式api依赖:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>fluent-hc</artifactId>
        <version>4.5.2</version>
    </dependency>

使用方式如下:

    String uri = "http://localhost:8081/sayHello2?username=李四2";

    String string = null;
    try {
        string = Request.Get(uri).execute().returnContent().asString(Charset.forName("utf-8"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("返回信息:");
    System.out.println(string);

效果:

file

RestTemplate

RestTemplate相对于在使用springcloud的开发人员来说就很简单明了了。RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

RestTemplate提供的API很丰富

file

在springcloud架构的微服务中,直接引用即可:

@RestController
@RequestMapping("/user")
public class UsreController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/order/{id}")
    public List<Order> getOrdersById(@PathVariable("id") int id){
        List<Order> list =  restTemplate.getForObject("http://order-server/order/user/"+id,List.class);
        return list;
    }
}

引申:RPC与分布式服务框架的区别

rpc实现了服务消费者调用方client与服务提供方server之间的点对点调用方式,调用方与服务方一般采用直连的调用方式。

而分布式服务框架,除了包括RPC的特性之外,还包括多台server提供服务的负载均衡策略以及实现方式,服务注册,发布与引入,服务治理,网关等特性。

总得来说,分布式服务框架包含了RPC的特性。

本人水平有限,难免有错误或遗漏之处,望大家指正和谅解,提出宝贵意见,愿与之交流。

推荐阅读
关注数
0
文章数
16
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息