微服务~远程调用HttpClient入门
Posted 陶然同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微服务~远程调用HttpClient入门相关的知识,希望对你有一定的参考价值。
🔎这里是【微服务~远程调用】,关注我学习云原生不迷路
👍如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位🔎点赞👍评论收藏⭐️
👀专栏介绍
【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。
👀本期介绍
本期主要介绍微服务~远程调用
文章目录
概述
前言
2个团队,分别开发了“商品管理系统”和“用户管理系统”
问题:“商品管理系统”需要使用“用户管理系统”某个功能,怎么办?
根据用户的会员等级,显示不同的打折
什么是远程调用
-
客户端程序通过接口调用服务端程序,并获得该服务返回的数据的过程,称为远程调用。
-
“商品管理系统”调用“用户管理系统”的过程,就是“远程调用”。此时“商品管理系统”相当于模拟“浏览器”。
调用方式
-
常见的远程调用方式有2种:
-
RPC:Remote Produce Call远程过程调用,==自定义数据==格式的远程调用方式。基于原生TCP通信,速度快,效率高。
-
Http:采用http协议远程调用方式,==规定==了数据传输的格式,缺点是消息封装臃肿。现在热门的Rest风格,就可以通过http协议来实现。
-
-
常见框架 :
-
RPC常见框架: dubbo、WebService
-
Http常见框架:HttpClient、RestTemplate
-
区别 | HTTP | RPC |
---|---|---|
速度 | 较慢 | 快 |
难度 | 简单 | 复杂 |
灵活性 | 灵活,跨平台、跨语言 |
如何选择
-
那么我们该怎么选择呢?
-
==微服务==,基于Spring Cloud的微服务,更加强调的是独立、自治、灵活,一般都会采用
基于Http
的Rest风格服务。
-
搭建环境
父项目
-
项目名:nacos-parent-2.1
-
添加坐标:
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>2.3.5.RELEASE</version>
</parent>
<properties>
<spring.cloud.version>Hoxton.SR12</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.7-SNAPSHOT</spring.cloud.alibaba.version>
<mybatis.plus.starter.version>3.4.0</mybatis.plus.starter.version>
<durid.starter.version>1.1.10</durid.starter.version>
<swagger.version>2.7.0</swagger.version>
<jwt.jjwt.version>0.9.0</jwt.jjwt.version>
<jwt.joda.version>2.9.7</jwt.joda.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>$spring-boot.version</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>$spring.cloud.version</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>$spring.cloud.alibaba.version</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>$mybatis.plus.starter.version</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>$durid.starter.version</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>$swagger.version</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>$swagger.version</version>
</dependency>
</dependencies>
</dependencyManagement>
测试数据项目
环境
-
项目:nacos-data
-
添加依赖
<dependencies>
<!--web起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--支持lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
- yml配置
server:
port: 7778
-
拷贝BaseResult 和 Swagger2ConfigurationV3
-
编写启动类
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by liangtong.
*/
@SpringBootApplication
public class DataApplication
public static void main(String[] args)
SpringApplication.run(DataApplication.class, args);
基本功能
-
创建JavaBean
package com.czxy.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by liangtong.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User
private Integer uid;
private String username;
private String password;
private Integer age;
- 编写基本功能(模拟数据)
package com.czxy.controller;
import com.czxy.domain.User;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liangtong.
*/
@RestController
@RequestMapping("/user")
public class UserController
@GetMapping
public BaseResult findAll()
List<User> list = new ArrayList<>();
list.add(new User(1,"jack","1234",18));
list.add(new User(2,"rose","5678",21));
list.add(new User(3,"tom","6666",25));
return BaseResult.ok("查询所有",list);
@GetMapping("/uid")
public BaseResult findById(@PathVariable("uid")Integer uid)
User user = new User(1,"jack","1234",18);
return BaseResult.ok("查询成功",user);
@GetMapping("/search")
public BaseResult search(User user)
System.out.println(user);
return BaseResult.ok("查询成功",user);
@PostMapping
public BaseResult save(@RequestBody User user)
System.out.println(user);
// return ResponseEntity.status(302).body(BaseResult.ok("添加成功"));
return BaseResult.ok("添加成功");
@PutMapping
public BaseResult update(@RequestBody User user)
System.out.println(user);
return BaseResult.ok("更新成功");
@DeleteMapping("/uid")
public BaseResult deleteById(@PathVariable("uid")Integer uid)
System.out.println(uid);
return BaseResult.ok("删除成功");
测试
HttpClient入门
概述
-
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
搭建环境
-
创建项目:nacos-http
-
pom配置
<dependencies>
<!--web起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!--支持lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
- 创建启动类
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HttpApplication
public static void main(String[] args)
SpringApplication.run(HttpApplication.class, args);
- 编写测试类
package com.czxy;
public class TestHttp
基本功能
GET请求--无参:查询所有
-
以get请求的方式,获得所有结果
-
1.创建客户端 (相当于打开浏览器)。CloseableHttpClient
-
2.创建GET请求实例(确定访问路径) HTTPGet
-
3.发送请求(回车访问)execute
-
4.判断响应的状态码200
-
5.通过工具处理响应内容
-
6.关闭资源
-
- 代码
@Test
public void testFindAll()
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://localhost:7778/user");
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
String str = EntityUtils.toString(response.getEntity());
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
- 如果响应的数据乱码,需要手动设定
练习:GET请求:查询详情
@Test
public void testFindId()
String id = "1";
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://localhost:7778/user/" + id);
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
GET请求--有参:拼凑URL
-
基本使用
@Test
public void testDemo03()
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
StringBuilder params = new StringBuilder();
params.append("username=张三");
params.append("&");
params.append("password=1234");
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://localhost:7778/user/search" + "?" + params.toString());
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
// 3.1 获得响应数据的类型
System.out.println(response.getEntity().getContentType());
// 3.2 获得响应体内容
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
-
拼凑特殊数据:URL中的特殊符号,需要使用URLEncoder处理
@Test
public void testDemo04()
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
StringBuilder params = new StringBuilder();
params.append("username=" + URLEncoder.encode("&","UTF-8"));
params.append("&");
params.append("password=1234");
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpGet httpGet = new HttpGet("http://localhost:7778/user/search" + "?" + params.toString());
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
// 3.1 获得响应数据的类型
System.out.println(response.getEntity().getContentType());
// 3.2 获得响应体内容
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
POST请求:手动拼凑JSON
@Test
public void testInsert()
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpPost httpPost = new HttpPost ("http://localhost:7778/user/");
// 2.1 准备json数据
String jsonStr = "\\n" +
" \\"uid\\": \\"1\\",\\n" +
" \\"username\\": \\"jack\\",\\n" +
" \\"password\\": \\"1234\\",\\n" +
" \\"age\\": \\"18\\"\\n" +
" ";
// 2.2 设置请求体
httpPost.setEntity(new StringEntity(jsonStr,"UTF-8"));
// 2.3 设置请求数据类型为json
httpPost.setHeader("content-type","application/json;charset=UTF-8");
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
POST请求:fastjson
-
fastjson 是阿里巴巴提供最快的json转换工具
-
如果要使用fastjson,修改pom.xml文件,添加坐标(如果已有,忽略此步)
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
-
拷贝JavaBean:User
-
代码
@Test
public void testInsert2()
try
//1 创建Httpclient对象,相当于打开了浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2 确定请求方式和请求路径,相当于在浏览器输入地址
HttpPost httpPost = new HttpPost ("http://localhost:7778/user/");
// 2.1 准备json数据
User user = new User(1,"jack","1234",18);
String jsonStr = JSON.toJSONString(user);
// 2.2 设置请求体
httpPost.setEntity(new StringEntity(jsonStr,"UTF-8"));
// 2.3 设置请求数据类型为json
httpPost.setHeader("content-type","application/json;charset=UTF-8");
//3 执行请求并获取响应,相当于敲完地址后按下回车。
CloseableHttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
String str = EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println(str);
response.close();
httpClient.close();
catch (IOException e)
e.printStackTrace();
以上是关于微服务~远程调用HttpClient入门的主要内容,如果未能解决你的问题,请参考以下文章
※Spring全家桶从入门到X神-微服务+远程调用(RestTemplate)