SpringCloud first experience

Source address: https://gitee.com/peachtec/springcloud The
  last chapter talked about some theories about SpringCloud, and today I started to upload the code for demonstration. There are compatibility issues between SpringCloud and SpringBoot versions, so you must pay attention to the choice of version when creating a project.
  

1. Create an ordinary maven project and use this project to manage other functional modules

Insert picture description here

2. After the project is created, configure the pom.xml file and import the required jar package

Import the jar packages needed by the project in the parent project for unified management. The subprojects only need to be quoted, and there is no need to manage the versions. All jar package versions are managed in the parent project.

<!-- 打包方式 pom-->
<packaging>pom</packaging>
<!-- 全局属性,比如说版本号可以在这里进行统一管理-->
<properties>
    <spring.cloud.version>Hoxton.SR9</spring.cloud.version>
    <spring.boot.version>2.3.5.RELEASE</spring.boot.version>
    <mysql.version>8.0.22</mysql.version>
    <druid.version>1.2.3</druid.version>
    <mybatis.plus.version>3.4.1</mybatis.plus.version>
    <junit.version>4.13.1</junit.version>
    <lombok.version>1.18.16</lombok.version>
    <log4j.version>1.2.17</log4j.version>
</properties>
<!-- jar包依赖管理 -->
<dependencyManagement>
    <dependencies>
        <!-- SpringCloud -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring.cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- SpringBoot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring.boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- MySQL数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis.plus.version}</version>
        </dependency>
        <!-- junit单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>
3. Create the first maven module, this module is mainly used to manage entity classes in this example

Note that the parent project selects the previously created project when creating
Insert picture description here

4. Configure the first module: the pom.xml file of the entity class module, import dependencies

The imported jar package, if the version is defined in the parent project, you do not need to specify the version number if you import it in the submodule; and, if the submodule is created correctly and successfully references the parent project, it will be in the pom.xml file of the parent project See the current module coordinates, as shown in the figure below.
Insert picture description here
Because it is a management entity class, just import a lombok, or directly write set and get without importing

<!-- 当前module的jar包依赖 -->
<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
5. Create the required entity classes

It seems that I forgot to create a database

drop database if exists db01;
create database if not exists db01 default character set utf8mb4 collate utf8mb4_general_ci;
use db01;

drop table if exists `dept`;
create table if not exists `dept`
(
    `id`        int primary key auto_increment comment '编号',
    `name`      varchar(60) not null comment '部门',
    `db_source` varchar(20) not null comment '数据库名'
) comment '部门表';
insert into dept (name, db_source)
values ('开发部', database()),
       ('人事部', database()),
       ('市场部', database()),
       ('销售部', database()),
       ('运维部', database()),
       ('行政部', database());

If you don’t use lombok, use shortcut keys or write other methods. Note that because it is a network transmission, you must implement the Serializable interface to achieve serialization.

@Data
@Accessors(chain = true) //链式编程
public class Dept implements Serializable {
    
    
    private Integer id;
    private String name;
    private String dbSource;
}
6. Create a second module, this module provides user services, which is the service layer of SpringBoot

Mainly select the parent project
Insert picture description here

7. Configure the second module: the pom.xml file of the service module, import dependencies
<dependencies>
<!-- 实体类模块坐标 -->
<dependency>
    <groupId>org.peach</groupId>
    <artifactId>springcloudentity</artifactId>
    <version>1.0</version>
</dependency>
<!-- 单元测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
</dependency>
<!-- 数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- springboot的测试 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test</artifactId>
</dependency>
<!-- web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jetty 应用服务器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<!-- 热部署工具 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
8. Configure the yaml file of the second module
server:
  port: 8001
mybatis-plus:
  type-aliases-package: com.peach.entity
  mapper-locations: classpath*:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
spring:
  application:
    name: springcloud-server
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://192.168.0.109/db01?useUnicode=true&characterEncoding=utf-8
9. Write the interface of the service class and implement it
//数据操作层
@Mapper
@Repository
public interface DeptMapper {
    
    }

//服务层
@Service
public class DeptService implements IDeptService {
    
    }

//控制层
@RestController
@RequestMapping("/dept")
public class DeptApi {
    
    
    @Autowired
    private IDeptService service;

    @PostMapping("/add")
    private boolean addDept(Dept dept){
    
    
        return service.addDept(dept);
    }
    @GetMapping("/get/{id}")
    private Dept queryById(@PathVariable Integer id){
    
    
        return service.queryById(id);
    }
    @GetMapping("/get")
    private List<Dept> queryAll(){
    
    
        return service.queryAll();
    }
}

//主启动类
@SpringBootApplication
public class Dept_8001 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Dept_8001.class, args);
    }
}

The project test starts and tests whether it can be accessed normally

10. Create a third module: consumer module, used to call the services provided by the second module

Pay attention to selecting the parent project
Insert picture description here

11. Configure the third module: the pom.xml file of the consumer module, import dependencies
<dependencies>
   <dependency>
       <groupId>org.peach</groupId>
       <artifactId>springcloudentity</artifactId>
       <version>1.0</version>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>
12. Configure the yaml file of the third module, just configure a port
server:
  port: 80
13. Add RestTemplate to the Spring container

  In Dubbo, we can call the remote interface through **@DubboReference , but in SpringCloud, RestFul style requests are used, so there is a RestTemplate** class, which contains the methods corresponding to the five commonly used request methods. , We can call it directly, but this class is useless to register in Spring by default, so we need to register it in the Spring container before use

@Configuration
public class RestTemplateConfig {
    
    

    @Bean
    public RestTemplate getRestTemplate(){
    
    
        return new RestTemplate();
    }
}
14. Consumer control layer interface

  SpringCloud is based on restful style requests. There is no service layer among consumers. You need to call interfaces of other layers. The methods have been encapsulated in the RestTemplate class, and we can use them directly; when a single service is used, the front end requests the backend url Address to obtain data; in SpringCloud, various methods encapsulated by RestTemplate, through these methods to call other URLs to obtain data,
  for example: public ResponseEntity getForEntity(String url, Class responseType, Object... uriVariables)
  url is the requested address, and The request address for a single service is the same, which is equivalent to RestTemplate to access this address.
  responseType is the type of the return parameter, and
  uriVariables is the parameter that needs to be passed in the request.

@RestController
@RequestMapping("/dept")
public class ConsumerApi {
    
    
    //注入RestTemplate
    @Autowired
    private RestTemplate restTemplate;
    /**
     * SpringCloud是基于restful风格的请求,在消费者中是没有服务层的,需要去调用其它层的接口
     * 在RestTemplate类已经封装好了方法,我们可以直接使用
     * 单一服务时,前端通过请求后端的url地址去获取数据
     * 在SpringCloud中,RestTemplate封装的各种方法,通过这些方法去调用其他的url去获取数据
     * 例如:public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables)
     * url是请求的地址,和单一服务时的请求地址一样,相当于RestTemplate去访问这个地址
     * responseType是返回参数的类型,
     * uriVariables是请求时需要传递的参数
     */
    /**
     * url的前缀
     */
    private static final String URL_PREFIX = "http://localhost:8001/dept";

    @GetMapping("/get/{id}")
    public Dept getDeptById(@PathVariable Integer id) {
    
    
        return restTemplate.getForObject(URL_PREFIX + "/get/" + id, Dept.class);
    }

    @PostMapping("/add")
    private boolean addDept(Dept dept) {
    
    
        return restTemplate.postForObject(URL_PREFIX + "/add", dept, boolean.class);
    }

    @GetMapping("/get")
    private List<Dept> queryAll() {
    
    
        return restTemplate.getForObject(URL_PREFIX + "/get", List.class);
    }
}

//主启动类
@SpringBootApplication
public class Resumer_80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Resumer_80.class, args);
    }
}
15. Start and test

  Start two services. There is no restriction on the order in which the two services are started. However, in order to avoid failure in the call, it is recommended to start the service provider first, and then start the service consumer

16. Attach a project structure at the end

This is the end of the first experience of SpringCloud. This is just a very simple example.
Insert picture description here
Source address: https://gitee.com/peachtec/springcloud

Guess you like

Origin blog.csdn.net/weixin_45481406/article/details/109907498