SpringCloud的认识和初步搭建

目录

一.认识SpringCloud

二.SpringCloud的部署

2.1开发环境

2.2数据库的建立

2.3SpringCloud的部署

第一步: 创建Maven项目

第二步:完善pom文件

第三步:创建两个子项目

第四步:声明项目依赖以及构建插件

第五步:完善子项目的代码

第六步:测试

2.4远程调用

三.总结RestTemplate


学习专栏:http://t.csdnimg.cn/tntwg

一.认识SpringCloud

        现在在Java当中最需要的技术就是SpringCloud,但是又该怎么学习呢? 我们先从它的定义入手!

        Spring Cloud 是一个用于构建分布式系统的开源框架,它提供了多种服务治理工具和组件,简化了基于 Spring Boot 的应用开发、部署、测试等方面的复杂性。

总结:SpringCloud把一个单体项目,拆分为多个微服务,每个微服务可以独立技术选型,独立开发,独立部署,独立运维.并且多个服务相互协调,相互配合。并且主要学习它的部署。以及各个组件!

组件:Eureka、LoadBalance、Nacos、OpenFeign、Gateway等

二.SpringCloud的部署

2.1开发环境

        我们需要JDK17以上的版本,MySQL也是需要8版本的,因此老版本需要淘汰了!

Linux安装JDK17和MySQL8教程:http://t.csdnimg.cn/0RxW9

2.2数据库的建立

        我们以数据的获取作为实例,来让我们部署SpringCloud更有依据性!

创建学校库:

create database if not exists cloud_teacher charset utf8mb4;
create database if not exists cloud_student charset utf8mb4;

cloud_teacher库下Teacher表:

create table teacher_detail (
    id int  COMMENT '工号',
    name varchar(8) NOT NULL COMMENT '姓名',
    sex varchar(4) NOT NULL,
    classroom varchar(20) NOT NULL,
    check (sex = 'boy' or sex = 'gril')
);
---插入数据
insert into teacher_detail values (2001,"TQ01","boy","21班"),(2002,"TQ02","gril","22班"),(2003,"TQ03","boy","23班"),(2004,"TQ04","gril","24班"),(2005,"TQ05","boy","25班");

cloud_student库下的Student表:

create table student_detail (
    id int  COMMENT '学号',
    name varchar(10) NOT NULL COMMENT '姓名',
    sex varchar(10) NOT NULL,
    classroom varchar(20) NOT NULL
);
---插入数据
insert into student_detail values (1,"zhangsan","boy","21班"),(2,"lisi","gril","21班"),(3,"wnagwu","boy","22班"),(4,"TQ04","gril","24班"),(5,"TQ05","gril","25班");

可自定义插入一些数据!

2.3SpringCloud的部署

第一步: 创建Maven项目

打开电脑的IDEA,选择创建Maven项目,然后删除src文件夹,保留pom.xml

目录结构:

第二步:完善pom文件

      使⽤properties来进⾏版本号的统⼀管理, 使⽤dependencyManagement来管理依赖, 声明⽗⼯程的打包⽅式为pom

<?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>org.example</groupId>
    <artifactId>Build</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
            <!--   SpringBoot的版本号     -->
        <version>3.1.6</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <java.version>17</java.version>
        <mybatis.version>3.0.3</mybatis.version>
        <mysql.version>8.0.33</mysql.version>
            <!--  Cloud版本      -->
        <spring-cloud.version>2022.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <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.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>com.mysql</groupId>
                <artifactId>mysql-connector-j</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>

                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter-test</artifactId>
                <version>${mybatis.version}</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

注:

1.DependencyManagement 和 Dependencies的区别:

  1. <dependencyManagement> 用于集中管理依赖的版本号,可以在父项目中定义,子项目可以继承并直接引用,避免重复指定版本号。
  2. <dependencies> 用于实际声明项目中所需的依赖,包括详细的依赖信息,如 groupId、artifactId 和特定的版本号(如果需要覆盖 <dependencyManagement> 中的版本号)。

2.在Spring官网里,明确规定了SpringBoot和SpringCloud的对应版本:

第三步:创建两个子项目

        创建2个子项目,分别为学生服务和老师服务

第四步:声明项目依赖以及构建插件

        在子项目的pom.xml当中插入这段代码! 定义依赖项

<dependencies>
     <dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
    <dependency>
         <groupId>com.mysql</groupId>
         <artifactId>mysql-connector-j</artifactId>
     </dependency>
             <!--mybatis-->
     <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         </dependency>
</dependencies>

<build>
     <plugins>
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
     </plugins>
</build>

        通过在父项目的 <dependencyManagement> 中定义这些依赖项,子项目可以简单地引用这些依赖,而无需重复指定版本号,只需指定 <groupId><artifactId> 即可。

第五步:完善子项目的代码

        目前创建成功,但是我们需要完善其中的代码:

 1.启动类   2.model层实体类   3.Controller层、.mapper层接口、.server层     4.配置文件

1.项目结构完善及启动类完善:

2.model层完善:

        和数据库的字段保持一致即可!

3.配置文件完善:

代码:

server:
  port: 8081
Spring:
  datasource:
      url: jdbc:mysql://127.0.0.1:3306/数据库名?characterEncoding=utf8&useSSL=false
      username: root
      password: 密码
      driver-class-name: com.mysql.cj.jdbc.Driver

# 设置 Mybatis 的 xml 保存路径
mybatis:
  configuration: # 配置打印 MyBatis 执行的 SQL
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true  #自动驼峰转换

4.包下完善

        这个完善,我是指写一个例子可以运行而已!

Student服务根据ID查找学生信息,

Teacher我根据教室查找老师的信息

Controller层:

@RequestMapping("/Student")
@RestController
public class StudentController {
    @Autowired
    StudentService studentService;
    @RequestMapping("/{studentId}")
    public StudentInfo getId(@PathVariable int studentId){
        return studentService.getId(id);
    }
}
@RestController
@RequestMapping("/Teacher")
public class TeacherController {

    @Autowired
    TeacherService teacherService;
    @RequestMapping({"/{classroom}"})
    public TeacherInfo getTeacherId(@PathVariable("classroom")String classroom){
        return teacherService.getclassroom(classroom);
    }
}

service层:

@Service
public class StudentService {
    @Autowired
    StudentMapper studentMapper;
    public StudentInfo getId(int id){
        return studentMapper.getId(id);
    }
}
@Service
public class TeacherService {
    @Autowired
    TeacherMapper teacherMapper;
    public TeacherInfo getclassroom(String classroom){
        return teacherMapper.getClassroom(classroom);
    }
}

mapper层:

@Mapper
public interface StudentMapper {
    @Select("select * from studentDetail where id = #{id}")
    StudentInfo getId(int id);
}
@Mapper
public interface TeacherMapper {
    @Select("select * from teacher_detail where classroom = #{classroom}")
    TeacherInfo getClassroom(String classroom);
}

第六步:测试

如图,返回成功!注意端口号之分 

2.4远程调用

        在上面,我们可以发现,这还是单机运行,各个项目运行自身的服务,获取信息,而SpringCloud体现在何处呢?接下来我们将在Student调用Teacher的Controller,并且获取到数据

我们先修改一下Student类,并且复制Teacher类添加到在Student-service的Model包中!

实现思路: Student-service服务向Teacher-service服务发送⼀个http请求, 把得到的返回结果, 和订单结
果融合在⼀起, 返回给调⽤⽅.
实现⽅式: 采⽤Spring 提供的RestTemplate

第一步:创建一个config包,添加BeanConfig 

@Configuration
public class BeanConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

第二步:修改Service包下的类

@Service
public class StudentService {
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    RestTemplate restTemplate;
    public StudentInfo getId(int id){
        StudentInfo studentInfo = studentMapper.getId(id);
        String url = "http:127.0.0.1:8081/Teacher/"+studentInfo.getClassroom();
        TeacherInfo teacherInfo = restTemplate.getForObject(url, TeacherInfo.class);
        studentInfo.setTeacherInfo(teacherInfo);
        return studentInfo;
    }
}

测试结果:

三.总结RestTemplate

        在本次实验中,我们可以发现项目和项目之间的http请求完全依靠于RestTemplate   那么是否可以说学会了这个RestTemplate,SpringCloud就掌握了呢?

不不不,SpringCloud是各个组件的学习,你只是初步认识到了SpringCloud的知识!

本次项目存在的问题:

  1. 远程调用时,URL的IP和端口号是写死的,想更换ip需要修改代码!
  2. 所有服务都可以调用该接口,这安全吗?
  3. RestTemplate被阻塞导致性能下降,怎么办呢?

前面两个都可以使用注册中心解决,但最后一个需要从自身上解决问题!

因阻塞而性能下降 :

方法一:

        RestTemplate 默认使用 SimpleClientHttpRequestFactory,可以配置连接池参数如最大连接数、连接超时、读取超时等,以优化连接管理,减少瓶颈。

RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create()
        .setMaxConnPerRoute(20)
        .setMaxConnTotal(50)
        .build()));

方法二:

        使用微服务网关(如 Spring Cloud Gateway)的方式!

当然也许有其他方法,但是我目前知识有限,以后学到了再补充吧

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

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

相关文章

Docker核心技术:容器技术要解决哪些问题

云原生学习路线导航页&#xff08;持续更新中&#xff09; 本文是 Docker核心技术 系列文章&#xff1a;容器技术要解决哪些问题&#xff0c;其他文章快捷链接如下&#xff1a; 应用架构演进容器技术要解决哪些问题&#xff08;本文&#xff09;Docker的基本使用Docker是如何实…

Ubuntu20.04从零开搭PX4MavrosGazebo环境并测试

仅仅是个人搭建记录 参考链接&#xff1a; https://zhuanlan.zhihu.com/p/686439920 仿真平台基础配置&#xff08;对应PX4 1.13版&#xff09; 语雀 mkdir -p ~/tzb/catkin_ws/src mkdir -p ~/tzb/catkin_ws/scripts cd catkin_ws && catkin init catkin build cd…

RV1103使用rtsp和opencv推流视频到网页端

参考&#xff1a; Luckfox-Pico/Luckfox-Pico-RV1103/Luckfox-Pico-pinout/CSI-Camera Luckfox-Pico/RKMPI-example Luckfox-Pico/RKMPI-example 下载源码 其中源码位置&#xff1a;https://github.com/luckfox-eng29/luckfox_pico_rtsp_opencv 使用git clone由于项目比较大&am…

共享模型之无锁

一、问题提出 1.1 需求描述 有如下的需求&#xff0c;需要保证 account.withdraw() 取款方法的线程安全&#xff0c;代码如下&#xff1a; interface Account {// 获取余额Integer getBalance();// 取款void withdraw(Integer amount);/*** 方法内会启动 1000 个线程&#xf…

纯净IP代理网站解析与代理推荐

一、纯净IP代理网站解析 在浩瀚的代理服务市场中&#xff0c;纯净IP代理以其特有的优势脱颖而出。它们不仅提供高质量、无污染的IP资源&#xff0c;还注重服务的稳定性和安全性&#xff0c;确保用户在使用过程中能够享受到好的网络体验。纯净IP代理的优势在于其能够有效解决因…

科技论文在线--适合练习期刊写作和快速发表科技成果论文投稿网站

中国科技论文在线这个平台可以作为练手的一个渠道&#xff0c;至少可以锻炼一下中文写作&#xff0c;或者写一些科研方向的简单综述性文章。当然&#xff0c;如果你的老师期末要求也是交一份科技论文在线的刊载证明的话&#xff0c;这篇文章可以给你提供一些经验。 中国科技论…

【引领未来智造新纪元:量化机器人的革命性应用】

在日新月异的科技浪潮中&#xff0c;量化机器人正以其超凡的智慧与精准的操作&#xff0c;悄然改变着各行各业的生产面貌&#xff0c;成为推动产业升级、提升竞争力的关键力量。今天&#xff0c;让我们一同探索量化机器人在不同领域的广泛应用价值&#xff0c;见证它如何以科技…

皇后游戏1

先把这个推导看完 现在我们来讲一下总结 首先&#xff0c;我们要观察到 c i c_i ci​递增&#xff0c;这样才能更简单&#xff0c;就不用像国王游戏那样在交换前后比较 i i i和 j j j的max了&#xff08;就是说&#xff0c;国王游戏需要比较 m a x ( c i , c j ) max(c_i,c_j)…

获取本地时间(Linux下,C语言)

一、函数 #include <time.h> time_t time(time_t *tloc);函数功能&#xff1a;获取本机时间&#xff08;以秒数存储&#xff0c;从1970年1月1日0:0:0开始到现在&#xff09;。返回值&#xff1a;获得的秒数&#xff0c;如果形参非空&#xff0c;返回值也可以通过传址调用…

政安晨【零基础玩转各类开源AI项目】基于Ubuntu系统部署Hallo :针对肖像图像动画的分层音频驱动视觉合成

目录 背景介绍 训练与推理 训练 推理 开始部署 1. 把项目源码下载到本地 2. 创建 conda 环境 3. 使用 pip 安装软件包 4. 下载预训练模型 5. 准备推理数据 6. 运行推理 关于训练 为训练准备数据 训练 政安晨的个人主页&#xff1a;政安晨 欢迎 &#x1f44d;点赞…

操作系统(3)——内存管理

目录 小程一言专栏链接: [link](http://t.csdnimg.cn/6grrU)内存管理无存储器抽象存储器抽象实现以下几方面小结 虚拟内存实现以下方面总结 页面置换算法概述常见的页面置换算法先进先出&#xff08;FIFO&#xff09;算法最近最少使用&#xff08;LRU&#xff09;算法总结 小程…

list(链表)容器的规则及list的高级排序案例

1.list的基本概念&#xff1a; 功能&#xff1a;将数据进行链式存储 list&#xff08;链表&#xff09;是一种物理存储单元上非连续的存储结构&#xff0c;数据元素的逻辑顺序是通过链表中的指针链接实现的 链表是由一系列节点组成&#xff0c;节点的组成包含存储数据元素的…

【保卫花果山】游戏

游戏介绍 拯救花果山是一款玩家能够进行趣味闯关的休闲类游戏。拯救花果山中玩家需要保护花果山的猴子&#xff0c;利用各种道具来防御妖魔鬼怪的入侵&#xff0c;游戏中玩家需要面对的场景非常的多样&#xff0c;要找到各种应对敌人的方法。拯救花果山里玩家可以不断的进行闯…

huawei USG6001v1学习----NAT和智能选路

目录 1.NAT的分类 2.智能选路 1.就近选路 2.策略路由 3.智能选路 NAT:&#xff08;Network Address Translation&#xff0c;网络地址转换&#xff09; 指网络地址转换&#xff0c;1994年提出的。NAT是用于在本地网络中使用私有地址&#xff0c;在连接互联网时转而使用全局…

在win10上通过WSL和docker安装Ubuntu子系统,并配置Ubuntu可成功使用宿主机GPU

本文主要记录win10系统上,通过WSL的Ubuntu系统以及Docker使用GPU的全部过程。 文章目录 1、 启用hyper-v2、 安装docker3、 安装WSL3.1 安装WSL23.1.1 检查是否安装了WSL23.1.1 安装和配置 WSL 23.2 安装Ubuntu 子系统3.3 检查并修改WSL版本4、docker配置ubuntu20.04 LTS5、下…

C语言函数:编程世界的魔法钥匙(2)-学习笔记

引言 注&#xff1a;由于这部分内容比较抽象&#xff0c;而小编我又是一个刚刚进入编程世界的计算机小白&#xff0c;所以我的介绍可能会有点让人啼笑皆非。希望大家多多包涵&#xff01;万分感谢&#xff01;待到小编我学有所成&#xff0c;一定会把这块知识点重新介绍一遍&a…

零基础STM32单片机编程入门(十五) DHT11温湿度传感器模块实战含源码

文章目录 一.概要二.DHT11主要性能参数三.DHT11温度传感器内部框图四.DTH11模块原理图五.DHT11模块跟单片机板子接线和通讯时序1.单片机跟DHT11模块连接示意图2.单片机跟DHT11模块通讯流程与时序 六.STM32单片机DHT11温度传感器实验七.CubeMX工程源代码下载八.小结 一.概要 DH…

ubuntu20.04支持win10远程桌面连接

1. 安装xrdp sudo apt install xrdp 2. 检查xrdp状态 sudo systemctl status xrdp 要处于running状态 3.&#xff08;若为Ubuntu 20&#xff09;添加xrdp至ssl-cert sudo adduser xrdp ssl-cert 4. 重启服务 sudo systemctl restart xrdp 5. window 远程桌面连接&am…

“信息科技风险管理”和“IT审计智能辅助”两个大模块的部分功能详细介绍:

数字风险赋能中心简介 数字风险赋能中心简介 &#xff0c;时长05:13 大家好&#xff01;我是AI主播安欣&#xff0c;我给大家介绍一下数字风险赋能中心。 大家都知道当前我国政企机构的数字化转型已经进入深水区&#xff0c;数字化转型在给我们带来大量创新红利的同时&#xf…

【BUG】已解决:requests.exceptions.ProxyError: HTTPSConnectionPool

已解决&#xff1a;requests.exceptions.ProxyError: HTTPSConnectionPool 目录 已解决&#xff1a;requests.exceptions.ProxyError: HTTPSConnectionPool 【常见模块错误】 原因分析 解决方案 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&am…