Spring Cloud framework (native Hoxton version and Spring Cloud Alibaba) basic introduction ---- build the environment

Springcloud official document (Hoxton SR5): https://cloud.spring.io/spring-cloud-static/Hoxton.SR5/reference/htmlsingle/
springcloud Chinese document: https://www.springcloud.cc/
springcloud Chinese community document : http://docs.springcloud.cn/
https://www.bookstack.cn/read/spring-cloud-docs/docs-index.md

insert image description here

1. Introduction to Spring Cloud

Spring Cloud is an ordered collection of a series of frameworks. It uses the development convenience of Spring Boot to subtly simplify the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring, etc., can all be done with the development style of Spring Boot to one-click launch and deployment. Spring Cloud does not repeat manufacturing wheels, it just combines mature and practical service frameworks developed by various companies, and repackages through Spring Boot style to shield complex configuration and implementation principles, and finally gives developers The author has left a set of distributed system development kits that are easy to understand, easy to deploy, and easy to maintain.

Spring Cloud focuses on providing a good out-of-the-box experience for typical use cases and extension mechanisms to cover other situations.

  • Distributed/versioned configuration
  • Service Registration and Discovery
  • routing
  • service-to-service call
  • load balancing
  • breaker
  • distributed messaging

insert image description here

Spring Cloud is a one-stop solution for distributed micro-service architecture. It is a collection of various micro-service architecture landing technologies, commonly known as micro-service family bucket

Jingdong internal microservice architecture

insert image description here
insert image description here

General microservice technology stack

insert image description here
insert image description here

Spring Cloud and Spring Boot version dependencies

Spring cloud official website address: https://spring.io/projects/spring-cloud

insert image description here

Learning Environment Version

  • jdk 1.8
  • maven 3,5 and above
  • mysql 5.7 or above
  • Spring Cloud Hoxton.SR1
  • Spring Cloud Alibaba 2.1.0
  • Spring Boot 2.2.2

Regarding the suspension/upgrade/replacement of various components of Cloud

insert image description here

2. Microservice architecture coding implementation

Conventions > Configuration > Encoding

Build the overall parent project of microservices

  1. Create New Project

insert image description here

  1. Fill in the project name

insert image description here
3. Check local maven

insert image description here

4. Set the project encoding

insert image description here

5. Set annotation activation to take effect

insert image description here

6. Java compiled version modification

insert image description here

Parent project pom file

<packaging>pom</packaging>

insert image description here

All dependency trees required by the project

<?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.zhao.springcloud</groupId>
    <artifactId>cloud2020</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    <!--统一管理jar包版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <lombok.version>1.18.10</lombok.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>8.0.18</mysql.version>
        <druid.version>1.1.20</druid.version>
        <mybatis.spring.boot.version>1.3.2</mybatis.spring.boot.version>
    </properties>

    <!--子模块继承之后,提供作用:锁定版本+子module不用写groupId和version-->
    <dependencyManagement>
        <dependencies>
            <!--spring boot 2.2.2-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud Hoxton.SR1-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
                <scope>runtime</scope>
            </dependency>
            <!-- druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!--log4j-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
        </dependencies>

    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

The difference between dependencyManagement and dependencies in Maven

insert image description here
In the subproject, if not specified, the default is the same as the version in the dependencyManagement tag of the parent project, and the dependencyManagement tag of the parent project only specifies the version number, and the specific import of dependencies is still imported by the subproject.
insert image description hereSkip unit tests in maven:

insert image description here

Rest microservice engineering construction

The simplest payment module

insert image description here
Build steps:

  1. build module
  2. change pom
  3. write yml
  4. main boot
  5. business class
  6. test

1. Microservice provider payment module module cloud-provider-payment8001

create module

insert image description here
insert image description here
Fill in the module name

insert image description here
Created

insert image description here

Add dependency tree

<?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">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>com.zhao.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-payment-8001</artifactId>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>

Write yml file

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service
    #数据库配置
    datasource:
      type: com.alibaba.druid.pool.DruidDataSource
      #mysql5.x的没有cj
      driver-class-name: com.mysql.cj.jdbc.Driver
      #记得先创建数据库
      url: jdbc:mysql://localhost:3306/db2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456

    #mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.zhao.springcloud.entities  #所有Entity别名类所在包

Write the main startup class

@SpringBootApplication
public class PaymentMain8001 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(PaymentMain8001.class);
    }
}

write business class

1. Create a database

CREATE TABLE `payment`(
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
	`serial` VARCHAR(200) DEFAULT '',
	PRIMARY KEY(`id`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO payment(`serial`)VALUES("xxx");

2. Create an entity class

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PayMent implements Serializable {
    
    
    private Long id;
    private String serial;
   
}

Return the front-end json data object

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    
    
    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code, String message) {
    
    
        this.code = code;
        this.message = message;
    }
}

3. Persistence layer (dao)
persistence layer interface:

@Mapper
public interface PaymentDao {
    
    

    int add(Payment payment);

    //  加上@Param注解,mapper中就可以采用#{}的方式把@Param注解括号内的参数进行引用
    Payment getPaymentById(@Param("id") Long id);
}

mapper.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zhao.springcloud.dao.PaymentDao">

    <insert id="add" parameterType="com.zhao.springcloud.entities.Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) value (#{serial})
    </insert>

    <select id="getPaymentById" parameterType="long" resultMap="BaseResultMap">
        select * from payment where id = #{id}
    </select>
    <resultMap id="BaseResultMap" type="com.zhao.springcloud.entities.Payment">
        <!--column 数据库字段   property Java字段-->
        <id column="id" property="id" jdbcType="BIGINT"></id>
        <result column="serial" property="serial" jdbcType="VARCHAR" />
    </resultMap>
</mapper>

4. Service layer (service)
service layer interface

public interface PaymentService {
    
    

    int add(Payment payment);

    Payment getPaymentById(@Param("id") Long id);

}

Implementation class

@Service
public class PaymentServiceImpl implements PaymentService {
    
    

    @Resource
    private PaymentDao paymentDao;

    @Override
    public int add(Payment payment) {
    
    
        return paymentDao.add(payment);
    }

    @Override
    public Payment getPaymentById(Long id) {
    
    
        return paymentDao.getPaymentById(id);
    }
}

5. Controller

@RestController
@Slf4j
public class PaymentController {
    
    
    @Resource
    private PaymentService paymentService;

    @PostMapping("/payment/add")
    public CommonResult<Payment> add(@RequestBody Payment payment){
    
    
        int result = paymentService.add(payment);
        log.info("******插入结果:"+result);
        if (result>0){
    
    
            return new CommonResult(200,"插入数据库成功",result);
        }else {
    
    
            return new CommonResult(444,"插入数据库失败",null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
    
    
        Payment payment = paymentService.getPaymentById(id);
        log.info("******插入结果:"+payment);
        if (payment != null){
    
    
            return new CommonResult(200,"查询成功",payment);
        }else {
    
    
            return new CommonResult(444,"没有当前查询记录,查询id"+id,null);
        }
    }

}

test

Start the project, enter the browser, http://localhost:8001/payment/get/1and the query is successful

insert image description here

Because browsers generally do not support sending post requests directly, you need to use the tool apiPost for testing
insert image description here

Enter http://localhost:8001/payment/addand send a post request to insert a piece of data into the database, and the data needs to be written into the body.

insert image description here
insert image description here

2. Hot deployment Dev-tools

Add dependencies to subprojects

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

Parent project add plugin

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

Enable automatic compilation permissions

insert image description here
Hotkey Registration On

insert image description here

Restart IDEA to take effect! !

3. Microservice consumer order module cloud-consumer-order80

new module

insert image description here
add dependencies

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Create a new yml file

server:
  port: 80
  

main startup class

@SpringBootApplication
public class OrderMain80 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderMain80.class);
    }
}

Business class
① Copy the entities in the cloud-provider-payment8001 project

insert image description here
② Add configuration class

@Configuration
public class ApplicationContextConfig {
    
    

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

③ Create a controller

@RestController
@Slf4j
public class OrderController {
    
    

    public static final String PAYMENT_URL = "http://localhost:8001";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/add")
    public CommonResult<Payment> add(Payment payment){
    
    
        return restTemplate.postForObject(PAYMENT_URL+"/payment/add",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
    
    
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get"+id,CommonResult.class);
    }
}

test

Start two projects for testing. After both are started, a services prompt will pop up in the lower right corner, click show.

insert image description here

The user pays for the order, calls between services, enters the address http://localhost/consumer/payment/get/1, and the query is successful

insert image description here
The adding operation shows that the addition is successful on the page, and the database data is normal

insert image description here
insert image description here

4. Engineering reconstruction

Since the two microservice projects currently built have duplicate parts, they need to be extracted, packaged once, and run everywhere, so the projects are refactored.

new module

insert image description here

add dependencies

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--   一个Java工具包     -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.1</version>
        </dependency>
    </dependencies>

Put the entity class into the commons module

insert image description here

This project is packaged

insert image description here

Delete entities in 80 and 8001 and introduce custom dependencies

        <!--引入自定义的api通用包,使用payment实体-->
        <dependency>
            <groupId>com.zhao.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

insert image description here

reboot, and test

insert image description here
Query data successfully!

insert image description here
Insert data successfully!

insert image description here
insert image description here

At this point, the basic introduction to the Spring Cloud framework (native Hoxton version and Spring Cloud Alibaba) is over

Guess you like

Origin blog.csdn.net/Zp_insist/article/details/127764496