01 SpringCloud beginner

Mr. Zhou Yang's spring cloud

Sort out the notes of current study to facilitate your review. If there are deficiencies, please correct them.

Suspension / upgrade / replacement of various Cloud components

SpringCloud = a one-stop solution for distributed microservice architecture, which is a collection of landing technologies of a variety of microservice architectures, commonly known as microservice architecture

SpringBoot is a service development technology

Service registration and discovery: EUREKA

Service load balancing and invocation: NETFLIX OSS RIBBON

Service load and invocation: Netflix

Service degradation: HYSTRIX

Service gateway: Zuul

Service distributed configuration: SpringCloud Config

Service development: SpingBoot

Springboot version 2.0 and springcloud version h strongly recommend using springboot version 2.0 or above

Click LEARN on the official website of spring cloud to see the latest spring cloud, and then click Reference.Doc to see the corresponding Boot version of Sprng Cloud

POM of parent project

Delete the src directory and add it to pom

<packaging>pom</packaging>

Then replace all under < packaging > POM < / packaging > with the following.

 <!-- unified management  jar Package version -->
  <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>
    <log4j.version>1.2.17</log4j.version>
    <lombok.version>1.16.18</lombok.version>
    <mysql.version>5.1.47</mysql.version>
    <druid.version>1.1.16</druid.version>
    <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
  </properties>

  <!-- 1,Only the dependency is declared, not actually introduced. The dependency used by the subproject is declared on demand -->
  <!-- 2,Child projects can inherit from parent projects version and scope -->
  <!-- 3,Sub project if specified version and scope´╝îSubject to subproject -->
  <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 2.1.0.RELEASE-->
      <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>

      <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>
      <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis.spring.boot.version}</version>
      </dependency>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
      </dependency>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
        <optional>true</optional>
      </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>

Dependency management tag in maven:

Using the dependency management tag, you can make all child projects reference a dependency list Maven that does not need to be displayed. Maven will go up the parent-child hierarchy until a dependency management project is found

If you do not specify a version number in a child project, it is the same as the version in the dependency management tag of the parent project by default, and the dependency management tag of the parent project only specifies the version number, whether to import dependency or child project.

This can avoid declaring a version number in each used sub project. When upgrading or switching to another version, you only need to update it in the top-level parent

Payment module

The order module (port number: 80) calls the payment module (port number: 8001)

Steps:

  1. Create module
  2. Change pom
  3. Write yml
  4. Main start
  5. Business class
  6. test

Create a new module

Sub project name: cloud provider payment8001

A modules tag appears in the pom of the parent class

  <modules>
    <module>cloud-provider-payment8001</module>
  </modules>

Add dependency in subclass pom

<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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
            <!--If the version number of the subproject is written, the version number of the subproject is used. If the version number is not written,Find the version number specified in the parent project-->
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--Hot deployment-->
        <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 the application.yml file in the resources directory

#It is recommended to write the service port number and microservice name
server:
  port: 8001

spring:
  application:
    #Microservice name
    name: Cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    #mysql5.x does not have cj
    driver-class-name: com.mysql.jdbc.Driver
    #Remember to create the database first
    url: jdbc:mysql://localhost:3306/db2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

#mybatis configuration
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.angenin.springcloud.entities  #Package of all Entity alias classes


Business class

1. Table building

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("Zhang San");

2. entities layer

Entity class package

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Payment {

    private Long id;
    private String serial;
}

Create a new CommonResult (json package, passed to the front end) under the entities package

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {

    private Integer code;
    private String message;
    private T      data;

    ////Customize the construction method of two parameters
    public CommonResult(Integer code,String message){
        this(code,message,null);
    }
}

3.dao layer

@Mapper
public interface PaymentDao {

    public int create(Payment payment);

    public Payment getPaymentById(Long id);
}

Create a mapper directory under resources, and then create PaymentMapper.xml

mapper is configured in the configuration 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.atguigu.springcloud.dao.PaymentDao">

<!--   Number returned after successful insertion > 0 So when you return a value iny -->
    <insert id="create" parameterType="Payment" useGeneratedKeys="true">
        insert into payment(serial) values(#{serial});
    </insert>

<!--  It is recommended to use interface set mapping to avoid name inconsistency  -->
    <resultMap id="BaseResultMap" type="com.atguigu.springcloud.entities.Payment">
        <id column="id" property="id" jdbcType="BIGINT"></id>
        <id column="serial" property="serial" jdbcType="VARCHAR"></id>
    </resultMap>

    <select id="getPaymentById" resultMap="BaseResultMap">
        select * from payment where id=#{id};
    </select>

</mapper>

4. service layer

public interface PaymentService {
    public int create(Payment payment);

    public Payment getPaymentById(Long id);
}

Create a new impl.PaymentServiceIpml implementation class under the service package

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource //java comes with @ Autowired
    private PaymentDao paymentDao;

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

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

5. controller layer

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @PostMapping("/payment/create")
    public CommonResult create(Payment payment){
        int result = paymentService.create(payment);
        log.info("Insert results"+result);
        if (result > 0){
            return new CommonResult(200,"Insert database succeeded",result);
        }else {
            return new CommonResult(444,"Insert database failed",null);
        }
    }

    @GetMapping ("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id")Long id){
        Payment payment = paymentService.getPaymentById(id);

        log.info("Insert results"+payment);
        if (payment != null){
            return new CommonResult(200,"query was successful",payment);
        }else {
            return new CommonResult(444,"Query failed, query ID: "+id,null);
        }
    }
}

Consumer order module

  1. Create a new module name: cloud-consumer-order80

  2. Change pom file

  3. yml file

    Add port

    server:
      port: 80
    
  4. Main start

  5. Write business

Consumers do not need to operate with the database

Copy the entities (two entity classes) in the cloud provider payment8001 project to the springcloud package of the project (cloud consumer order80).

Using RestTemplate

@Configuration
public class ApplicationContextConfig {

    //Add a RestTemplate to the container
    //RestTemplate provides a variety of convenient ways to access remote http access
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

controller layer

@RestController
@Slf4j
public class OrderController {

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

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        // //postForObject has three parameters: request address, request parameter and returned object type
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", 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);
    }
}

When idea starts two Services, it will be put into Services

If there is no services view - > tool windows - > services, start add in services

Consumers do not need to know that the port does not need to be added

Test: http://localhost/consumer/payment/get/11

http://localhost/consumer/payment/create?serial=123 Insert a piece of data.

Engineering reconstruction

The classes in the entities package in the system are the same. Take out the similar parts

1. Create a new module: cloud API Commons

2. pom join dependency

    <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>
        <!--   One Java tool kit     -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>

3. Copy entities to the project (the path needs to be the same. First create a package in the project, and then copy it)

4. Package the project

Clean before packing

maven packages the local project into a jar package through install, puts it into the local warehouse, and then introduces the dependency into the current project through pom.xml configuration.

  1. Delete the entities package for the other two items

  2. Introducing dependencies in pom files in two projects

       <dependency>
           <groupId>com.atguigu.springcloud</groupId>
           <artifactId>cloud-api-commons</artifactId>
           <version>${project.version}</version>
       </dependency>

Tags: Spring Cloud

Posted on Wed, 01 Dec 2021 21:09:50 -0500 by n_wattam