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)的方式!

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

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tq02

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值