SpringCloud微服务调用方式(RestTemplate)

服务调用方式

RPC和HTTP

无论是微服务还是SOA,都面临着服务间的远程调用。那么服务间的远程调用方式有哪些呢?

常见的远程调用方式有以下2种:

  • RPC:Remote Produce Call远程过程调用,类似的还有 。自定义数据格式,基于原生TCP通信,速度快,效率高。早期的webservice,现在热门的dubbo (12不再维护、17年维护权交给apache),都是RPC的典型代表

  • Http:http其实是一种网络传输协议,基于TCP,规定了数据传输的格式。现在客户端浏览器与服务端通信基本都是采用Http协议,也可以用来进行远程服务调用。缺点是消息封装臃肿,优势是对服务的提供和调用方没有任何技术限定,自由灵活,更符合微服务理念。现在热门的Rest风格,就可以通过http协议来实现。

跨域调用

跨域特指前端页面调用后端api,即前端页面在一个服务器,后端api在另外一个服务器,是浏览器安全保护行为,与后端没有关系。一般在前后端分离的项目中要解决跨域问题。解决跨域一般有以下几种方式:
(1)ajax+jsonp
(2)proxytable
(3)@CrossOrigin
(4)nginx代理
(5)response.setHeader(“Access-Control-Allow-Origin”, “*”);

远程调用

远程调用技术特指后端不同服务器之间的调用,例如在A服务的api中调用B服务的api。以下的技术都可以完成A服务调用B服务:
(1)dubbo+zookeeper
(2)springcloud中的eureka+feign
(3)httpclient/okhttp3
(4)spring中的RestTemplate
(5)webservice

搭建项目

创建project
在这里插入图片描述

在project(工程、项目)下点击创建module(模块)
在这里插入图片描述
选择好maven、选择好父包
在这里插入图片描述

创建模块
在这里插入图片描述

在父类模块中POM中引入WEB模块

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.woniu</groupId>
    <artifactId>moon-cloud-knife</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>moon-app-credit</module>
        <module>moon-app-knife</module>
        <module>moon-service-credit</module>
        <module>moon-service-login</module>
        <module>moon-service-order</module>
        <module>moon-service-product</module>
        <module>moon-service-gateway</module>
        <module>moon-common</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <spring.cloud.alibaba.version>2.2.5.RELEASE</spring.cloud.alibaba.version>
        <spring.boot.version>2.3.11.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR8</spring.cloud.version>
    </properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.12</version>
    </dependency>

    <!--        JSON-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
<dependencies>
    <!--Spring Cloud alibaba的版本管理, 通过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>
    <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>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring.boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.32</version>
    </dependency>


    <!--         fastjson-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.79</version>
    </dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>3.0.2</version>
        <configuration>
            <excludes>
                <exclude>
                    <groupId>org.projectlombok</groupId>
                    <artifactId>lombok</artifactId>
                </exclude>
            </excludes>
        </configuration>
    </plugin>
</plugins>
</build>

</project>

增加配置文件application.yml

image-20221109112541147

moon-app-credit

application.yml

server:
  port: 9000

CarController

@RestController
public class CarController{

   @Value("${server.port}")
    private String port;

    @RequestMapping(value = "/app/credit/{id}")
    public String provider(@PathVariable String id){
        return "credit id = " + id + " port = " + port;
    }

}

运行结果

image-20221109153509257

moon-service-product

application.yml

server:
  port: 8030

SkuController

@RestController
public class SkuController{

   @RequestMapping(value = "/TestSku/{id}")
    public String TestSku(@PathVariable String id){
        return "TestSku id="+id;
    }
}

运行结果

image-20221109153435407

HttpClient和OkHttp3性能比

  • client连接为单例:
    单例模式下,HttpClient的响应速度要更快一些,单位为毫秒,性能差异相差不大
  • 非单例模式下,OkHttp的性能更好,HttpClient创建连接比较耗时,因为多数情况下这些资源都会写成单例模式。
  • HttpClient+okhttp+URLConnection
    我新建一个test模块
    在这里插入图片描述

HttpClien

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
 import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
@RestController
public class TestController {

    /**
     * @title consumerHttp
     *
     * @param: id
     * @updateTime 2022/11/9 15:09
     * @return: java.lang.String
     * @throws
     * @Description: HttpClient调用方式
     */
    @RequestMapping(value = "/consumerHttp/{id}")
    public String consumerHttp(@PathVariable String id){
        String consumer = null;
        String url = "http://localhost:8030/TestSku/"+id;

        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            httpClient.executeMethod(getMethod);
            byte[] body = getMethod.getResponseBody();
            consumer = new String(body, "UTF-8");
        } catch (IOException e) {
            return "HttpClient consumer exception";
        }
        return "HttpClient consumer :http://localhost:8030/TestSku/id="+id+"~~~~" + consumer;
    }
    @RequestMapping("/test1008611")
    public String a(){
        return "lps";
    }

}


运行结果:

在这里插入图片描述

okhttp3

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.2</version>
</dependency>
    /**
     * @title consumerok
     *
     * @param: id
     * @updateTime 2023/05/20 10:25
     * @return: java.lang.String
     * @throws
     * @Description: OkHttpClient调用方式
     */
    @RequestMapping(value = "/consumerok/{id}")
    public String consumerok(@PathVariable String id){
        String consumer = null;
        String url = "http://localhost:8030/TestSku/"+id;

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            consumer = response.body().string();
        } catch (IOException e) {
            return "OkHttpClient consumer exception";
        }
        return "OkHttpClient调用方式,HttpClient consumer :http://localhost:8030/TestSku/id="+id+"~~~~" + consumer;
    }

运行结果:

image-20221109152448929

Spring的RestTemplate

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现

常用方法:

HTTP Method常用方法描述
GETgetForObject发起 GET 请求响应对象
GETgetForEntity发起 GET 请求响应结果、包含响应对象、请求头、状态码等 HTTP 协议详细内容
POSTpostForObject发起 POST 请求响应对象
POSTpostForEntity发起 POST 请求响应结果、包含响应对象、请求头、状态码等 HTTP 协议详细内容
DELETEdelete发起 HTTP 的 DELETE 方法请求
PUTput发起 HTTP 的 PUT 方法请求

声明restTemplateBean方式一

@Bean
public RestTemplate getRestTemplate(){
    return new RestTemplate();
}

声明restTemplateBean方式二

@Bean
public RestTemplate getRestTemplate(RestTemplateBuilder builder){
    return builder.build();
}

restTemplate远程调用

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @title consumerRest
     *
     * @param: id
     * @updateTime 2022/11/9 15:28
     * @return: java.lang.String
     * @throws
     * @Description: restTemplate调用方式
     */
     @RequestMapping(value = "/consumerRest/{id}")
    public String consumerRest(@PathVariable String id){
        String url = "http://localhost:8030/TestSku/"+id;
        String consumer = restTemplate.getForObject(url,String.class);
        return "restTemplate consumer如下=http://localhost:8030/TestSku/id="+id+"~~~~" + consumer;
    }

运行结果:

image-20221109153025784
没有设置负载均衡的话,启动类别加负载均衡的注解,@LoadBalanced,因为没有更改获取资源的路径,所以会报错
java.lang.IllegalStateException: No instances available for localhost

SpringCloud

微服务是一种架构方式,最终肯定需要技术架构去实施。

微服务的实现方式很多,目前Spring Cloud比较流行。为什么?

  • 后台硬:作为Spring家族的一员,有整个Spring全家桶靠山,背景十分强大。
  • 技术强:Spring作为Java领域的前辈,可以说是功力深厚,有强力的技术团队支撑。
  • 群众基础好:大多数程序员的成长都伴随着Spring框架,现在有几家公司开发不用Spring?SpringCloud与Spring的各个框架无缝整合,对大家来说一切都是熟悉的配方,熟悉的味道。
  • 使用方便:相信大家都体会到了SpringBoot给我们开发带来的便利,而SpringCloud完全支持SpringBoot的开发,用很少的配置就能完成微服务框架的搭建。

image-20221008093859011

简介

SpringCloud是Spring旗下的项目之一:

  • 官网地址:http://projects.spring.io/spring-cloud/
  • 中文地址:https://www.springcloud.cc/

Spring最擅长的就是集成,把世界上最好的框架拿过来,集成到自己的项目中。

SpringCloud也是一样,它将现在非常流行的一些技术整合到一起,实现了诸如:配置管理,服务发现,智能路由,负载均衡,熔断器,控制总线,集群状态等等功能。其主要涉及的组件包括:

  • Eureka:服务治理组件,包含服务注册中心,服务注册与发现机制的实现。(服务治理,服务注册/发现)
  • Zuul(gateway):网关组件,提供智能路由,访问过滤功能
  • Ribbon:客户端负载均衡的服务调用组件(客户端负载)
  • Feign(open feign):服务调用,给予Ribbon和Hystrix的声明式服务调用组件 (声明式服务调用)
  • Hystrix:容错管理组件,实现断路器模式,帮助服务依赖中出现的延迟和为故障提供强大的容错能力。(熔断、断路器,容错)

版本

因为Spring Cloud不同其他独立项目,它拥有很多子项目的大项目。所以它的版本是版本名+版本号 (如Angel.SR6)。

版本名:是伦敦的地铁名

版本号:SR(Service Releases)是固定的 ,大概意思是稳定版本。后面会有一个递增的数字。

所以 Edgware.SR3就是Edgware的第3个Release版本。

1528263985902

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/22344.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

learn C++ NO.4 ——类和对象(2)

1.类的6个默认成员函数 1.1.默认成员函数的概念 在 C 中&#xff0c;如果没有显式定义类的构造函数、析构函数、拷贝构造函数和赋值运算符重载函数&#xff0c;编译器会自动生成这些函数&#xff0c;这些函数被称为默认成员函数。 class Date { };初步了解了默认成员函数&am…

STL-常用算法(二.拷贝 替换 算术 集合)

开篇先附上STL-常用算法(一)的链接 STL-常用算法&#xff08;一.遍历 查找 排序&#xff09;_小梁今天敲代码了吗的博客-CSDN博客 目录 常用拷贝和替换算法&#xff1a; copy函数示例&#xff1a;&#xff08;将v1容器中的元素复制给v2&#xff09; replace函数示例&#…

Java 9 - 18 各个版本新特性总结

【 Java 9 - 18 各个版本新特性总结&#xff0c;B站视频介绍】https://www.bilibili.com/video/BV1PT411P7Wn?vd_source5a3a58ca0e99223ffb58cddf2f3a7282 一、模块化引入 模块是 Java 9 中新增的一个组件&#xff0c;可以简单理解为是package的上级容器&#xff0c;是多个pa…

gitlab建立新分支提交,cherry-pick部分更新

gitlab介绍 GitLab是一个基于Git的在线代码托管和协作平台&#xff0c;提供源代码管理、单元测试、CI/CD构建、代码审查等功能。它是一个开放源代码的Git仓库管理系统&#xff0c;使用 Ruby on Rails 构建GitLab 不仅具有自己的 Git 仓库管理系统&#xff0c;还具有很多其他的…

网络协议与攻击模拟-11-DHCP协议原理

DHCP 协议 1、掌握 DHCP 的工作原理 2、会在 Windows server 上去部署 DHCP 服务 3、抓流量 &#xff0e;正常 收到攻击后 一、 DHCP 1、 DHCP 基本概念 dhcp &#xff08;动态主机配置协议&#xff09;&#xff1a;主要就是给客户机提供 TCP / IP 参数&#xff08; IP 地…

App外包开发上线Google Play流程

完成App开发后需要在各大应用市场上线&#xff0c;国内的应用市场比较多&#xff0c;各自的规则也不相同&#xff0c;上线审核也比较复杂&#xff1b;国外上线主要是Google Play市场&#xff0c;它更重视隐私的保护&#xff0c;必须严格按照规范来保护个人隐私&#xff0c;因此…

【C++】模板的一点简单介绍

模板 前言泛型编程函数模板概念格式函数模板的原理函数模板的实例化 类模板类模板的定义格式类模板的实例化 前言 这篇博客讲的是模板的一些基本知识&#xff0c;并没有那么深入&#xff0c;但是如果你是为了过期末考试而搜的这篇博客&#xff0c;我觉得下面讲的是够了的。 之…

阿里云、腾讯云、移动云飙“价”:智能普惠成新风向?

经过过去一年的“低迷”境况之后&#xff0c;2023年云服务商因为AI大模型的爆发&#xff0c;重新燃起了斗志。站在当下的时间节点&#xff0c;云服务商们也在重新思考如何在新形势下&#xff0c;让自己占据更大的优势&#xff0c;于是一场围绕“技术竞争与市场争夺”的新战争打…

【总结】Numpy2

Numpy 1. 数组和数的运算 array1 np.arange(1,10) array1 # array([1, 2, 3, 4, 5, 6, 7, 8, 9]) array1 10 # array([11, 12, 13, 14, 15, 16, 17, 18, 19]) array1 - 10 # array([-9, -8, -7, -6, -5, -4, -3, -2, -1]) array1 * 10 # array([10, 20, 30, 40, 50, 60, 70…

3-《安卓基础》

3-《安卓基础》 一.Android系统架构二.四大组件1. Activity1.1 生命周期1.2. Activity四种启动模式1.3.Activity任务栈的概念1.4 面试题面试题1&#xff1a;onSaveInstanceState(Bundle outState)&#xff0c;onRestoreInstanceState(Bundle savedInstanceState) 的调用时机&am…

小黑子—Java从入门到入土过程:第十一章 - 网络编程、反射及动态代理

Java零基础入门11.0 网络编程1. 初识网络编程2. 网络编程三要素3.IP三要素3.1 IPV4的细节3.1.1特殊的IP地址3.1.2 常用的CMD命令 3.2 InetAddress 的使用3.3 端口号3.4 协议3.4.1 UDP协议3.4.1 - I UDP 发送数据3.4.1 - II UDP 接收数据3.4.1 - III UDP 练习&#xff08;聊天室…

前端列表页+element-puls实现列表数据弹窗功能

效果图&#xff1a; 这是一个修改的弹窗&#xff0c;我们要实现的功能是&#xff0c;在列表&#xff0c;点击修改按钮时&#xff0c;将数据带入到弹窗里面&#xff0c;点击保存时关闭弹窗。 1&#xff0c;点击修改展开弹窗 使用 eldialog组件&#xff0c;v-model绑定的值为tru…

Godot引擎 4.0 文档 - 入门介绍 - 学习新功能

本文为Google Translate英译中结果&#xff0c;DrGraph在此基础上加了一些校正。英文原版页面&#xff1a; Learning new features — Godot Engine (stable) documentation in English 学习新功能 Godot 是一个功能丰富的游戏引擎。有很多关于它的知识。本页介绍了如何使用…

迪赛智慧数——柱状图(基本柱状图):全球自动化无人机智能支出预测

效果图 全球自动化无人机智能支出及预测分析&#xff0c;2022年机器人流程自动化支出10.4十亿美元&#xff0c;智能流程自动化支出13十亿美元&#xff0c;人工智能业务操作达10.8十亿美元&#xff0c;未来&#xff0c;这些数字将进一步增长&#xff0c;自动化无人机智能也将拥有…

华为OD机试真题 Java 实现【天然蓄水池】【2023Q1 200分】

一、题目描述 公元2919年&#xff0c;人类终于发现了一颗宜居星球——X星。现想在X星一片连绵起伏的山脉间建一个天然蓄水库&#xff0c;如何选取水库边界&#xff0c;使蓄水量最大&#xff1f; 要求&#xff1a; 山脉用正整数数组s表示&#xff0c;每个元素代表山脉的高度。…

Java基础-面向对象总结(3)

本篇文章主要讲解Java面向对象的知识点 面向对象的三大特性类的扩展(抽象类,接口,内部类,枚举) 目录 面向对象和面向过程的区别? 面向对象的五大基本原则 面向对象三大特性 继承 怎么理解继承 ? 继承和聚合的区别&#xff1f; 封装 多态 什么是多态 什么是运行时多…

数字识别问题

文章目录 6.1 MNIST数据处理6.2.1 训练数据6.2.2 变量管理6.3.1 保存模型6.3.1 加载计算图6.3.1 加载模型6.3.2 导出元图 6.1 MNIST数据处理 在直接在第6章的目录下面创建文件 compat.v1.是tensorflow2.x的语法&#xff0c;全部删掉 删除compat.v1.后的代码 # -*- coding: …

基于最新SolVES 模型与多技术融合【QGIS、PostgreSQL、ARCGIS、MAXENT、R】实现生态系统服务功能社会价值评估及拓展案例分析

目录 第一章 理论基础与研究热点 第二章 SolVES 4.0 模型运行环境配置 第三章 SolVES 4.0 模型运行 第四章 数据获取与入库 第五章 环境变量与社会价值的相关分析 第六章 拓展案例分析 SolVES模型&#xff08;Social Values for Ecosystem Services&#xff09;全称为生态…

如何使用SolVES 模型与多技术融合实现生态系统服务功能社会价值评估?

生态系统服务是人类从自然界中获得的直接或间接惠益&#xff0c;可分为供给服务、文化服务、调节服务和支持服务4类&#xff0c;对提升人类福祉具有重大意义&#xff0c;且被视为连接社会与生态系统的桥梁。自从启动千年生态系统评估项目&#xff08;Millennium Ecosystem Asse…

SSL/TLS认证握手过程

一: SSL/TLS介绍 什么是SSL,什么是TLS呢&#xff1f;官话说SSL是安全套接层(secure sockets layer)&#xff0c;TLS是SSL的继任者&#xff0c;叫传输层安全(transport layer security)。说白点&#xff0c;就是在明文的上层和TCP层之间加上一层加密&#xff0c;这样就保证上层信…