这里是【微服务~远程调用】,关注我学习云原生不迷路
如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位点赞评论收藏⭐️
【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。
本期主要介绍微服务~远程调用
概述
前言
什么是远程调用
调用方式
搭建环境
父项目
测试数据项目
环境
基本功能
测试
HttpClient入门
概述
搭建环境
基本功能
GET请求--无参:查询所有
练习:GET请求:查询详情
GET请求--有参:拼凑URL
POST请求:手动拼凑JSON
POST请求:fastjso
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
添加坐标:
org.springframework.cloud
spring-cloud-build
2.3.5.RELEASE
Hoxton.SR12
2.2.7-SNAPSHOT
3.4.0
1.1.10
2.7.0
0.9.0
2.9.7
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.springframework.cloud
spring-cloud-dependencies
${spring.cloud.version}
pom
import
com.alibaba.cloud
spring-cloud-alibaba-dependencies
${spring.cloud.alibaba.version}
pom
import
com.baomidou
mybatis-plus-boot-starter
${mybatis.plus.starter.version}
com.alibaba
druid-spring-boot-starter
${durid.starter.version}
io.springfox
springfox-swagger2
${swagger.version}
io.springfox
springfox-swagger-ui
${swagger.version}
项目:nacos-data
添加依赖
org.springframework.boot
spring-boot-starter-web
io.springfox
springfox-swagger2
io.springfox
springfox-swagger-ui
org.projectlombok
lombok
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 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("删除成功");
}
}
http://localhost:7778/swagger-ui.html
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
创建项目:nacos-http
pom配置
org.springframework.boot
spring-boot-starter-web
org.apache.httpcomponents
httpclient
4.5.6
org.projectlombok
lombok
com.alibaba
fastjson
1.2.49
org.springframework.boot
spring-boot-starter-test
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请求的方式,获得所有结果
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();
}
}
@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();
}
}
基本使用
@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();
}
}
@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();
}
}
fastjson 是阿里巴巴提供最快的json转换工具
如果要使用fastjson,修改pom.xml文件,添加坐标(如果已有,忽略此步)
com.alibaba
fastjson
1.2.49
拷贝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();
}
}