第二章:微服务架构构建

2.1:IDEA新建project工作空间

  • 父工程步骤

    1. New Project

    2. 聚合总父工程名字

    3. Maven版本选择

    4. 字符编码

    5. 注解生效激活

    6. Java编译版本选择8

  • 父工程pom文件

    <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.wang.cloud</groupId>    <artifactId>cloud2022</artifactId>    <version>1.0-SNAPSHOT</version>    <packaging>pom</packaging>    <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>8.0.19</mysql.version>        <druid.version>1.1.16</druid.version>        <spring.boot.version>2.2.2.RELEASE</spring.boot.version>        <spring.cloud.version>Hoxton.SR1</spring.cloud.version>        <spring.cloud.alibaba.version>2.1.0.RELEASE</spring.cloud.alibaba.version>        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>    </properties>    <dependencyManagement>        <dependencies>                        <dependency>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-dependencies</artifactId>                <version>${spring.boot.version}</version>                <type>pom</type>                <scope>import</scope>            </dependency>                        <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>com.alibaba.cloud</groupId>                <artifactId>spring-cloud-alibaba-dependencies</artifactId>                <version>${spring.cloud.alibaba.version}</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.projectlombok</groupId>                <artifactId>lombok</artifactId>            </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>
  • Maven中的dependencyManagement

    1. Maven使用dependencyManagement元素来提供了一种管理依赖版本号的方式。通常会在一个组织或者项目的最顶层的父pom中看到dependencyManagement元素。
    2. 使用pom.xml中的dependencyManagement元素能让所有在子项目中引用一个依赖而不显示的列出版本号。Maven会沿着父子层次向上走,直到找到一个拥有dependencyManagement元素的项目,然后它就会使用这个dependencyManagement元素中指定的版本号。
    3. 这样做的好处就是:如果多个子项目都引用同一样的依赖,则可以避免在使用的子项目里都声明一个版本号,这样想升级或切换到另一个版本时,只需要在顶层父容器里更新,而不需要一个一个子项目的修改,另外如果某个子项目需要另外的一个版本,只需声明version版本。
    4. dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用依赖。

2.2:Rest微服务工程搭建

  • cloud-provider-payment8001微服务提供者Module模块

    1. 建module

      • 右键New Module,然后直接下一步

      • 模块命名

    2. 改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.10</version>        </dependency>                <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>                <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>        <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>
    3. 写YML

      server:  port: 8001spring:  application:    name: cloud-payment-service  datasource:    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包 com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/db2019    username: root    password: rootmybatis:  mapperLocations: classpath:mapper/*.xml  type-aliases-package: com.wang.cloud.entities    # 所有Entity别名类所在包
    4. 主启动

      package com.wang.cloud;@SpringBootApplicationpublic class PaymentMain8001 {    public static void main(String[] args) {        SpringApplication.run(PaymentMain8001.class, args);    }}
    5. 业务类

      • 创建数据库和表

        CREATE DATABASE db2022; 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
      • entities

        1. 主实体

          package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class payment implements Serializable {    private Long id;    private String serial;}
        2. Json封装体CommonResult

          package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class CommonResult<T> {    private Integer code;    private String message;    private T data;    public CommonResult(Integer code, String message) {        this(code, message, null);    }}
      • dao

        1. 接口PaymentDao

          package com.wang.cloud.dao;@Mapperpublic interface PaymentDao {    public int create(Payment payment);    public Payment getPaymentById(@Param("id") Long id);}
        2. mybatis的映射文件PaymentMapper.xml文件

          路径:src\main\resources\mapper\PaymentMapper.xml

          <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.wang.cloud.dao.PaymentDao">    <insert id="create" parameterType="Payment" useGeneratedKeys="true">        INSERT INTO payment(SERIAL) VALUES(#{serial});    </insert>    <resultMap id="BaseResultMap" type="com.wang.cloud.entities.Payment">        <id column="id" property="id" jdbcType="BIGINT" />        <result column="serial" property="serial" jdbcType="VARCHAR" />    </resultMap>    <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">        SELECT * FROM payment WHERE id=#{id};    </select></mapper>
      • service

        1. 接口PaymentService

          package com.wang.cloud.service;public interface PaymentService {    public int create(Payment payment);    public Payment getPaymentById(@Param("id") Long id);}
        2. 实现类

          package com.wang.cloud.service.impl;@Servicepublic class PaymentServiceImpl implements PaymentService {    @Resource    private PaymentDao paymentDao;    @Override    public int create(Payment payment) {        return paymentDao.create(payment);    }    @Override    public Payment getPaymentById(Long id) {        return paymentDao.getPaymentById(id);    }    }
      • controller

        package com.wang.cloud.controller;@RestController@Slf4jpublic class PaymentController {    @Resource    private PaymentService paymentService;    @PostMapping(value = "/payment/create")    public CommonResult create(Payment payment) {        int result = paymentService.create(payment);        log.info("*****插入操作返回结果:" + result);        if (result > 0) {            return new CommonResult(200, "插入数据成功", result);        } else {            return new CommonResult(200, "插入数据失败", null);        }    }    @GetMapping(value = "/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);        }    }}
  • 热部署Devtools

    1. Adding devtools to your project

      注:放在8001项目里,如果上方已经引入,此处可以不引入<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-devtools</artifactId>    <scope>runtime</scope>    <optional>true</optional></dependency>
    2. Adding plugin to your pom.xml

      注:放在父项目里,如果上方已经引入,此处可以不引入<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>
    3. Enabling automatic build

    4. update the value of

    5. 重启IDEA

  • cloud-consumer-order80微服务消费者订单Module模块

    1. cloud-consumer-order80模块

    2. 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.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>
    3. yml

      server:  port: 80
    4. 主启动

      package com.wang.cloud;@SpringBootApplicationpublic class MainApp80 {    public static void main(String[] args) {        SpringApplication.run(MainApp80.class, args);    }}
    5. 业务类

      • entities

        1. 主实体Payment

          package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class Payment implements Serializable {    private Long id;    private String serial;}
        2. Json封装体CommonResult

          package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class CommonResult<T> {    private Integer code;    private String message;    private T data;    public CommonResult(Integer code, String message) {        this(code, message, null);    }}
      • config配置类

        package com.wang.cloud.config;@Configurationpublic class ApplicationContextConfig {    @Bean    public RestTemplate restTemplate() {        return new RestTemplate();    }}
      • controller

        package com.wang.cloud.controller;@RestControllerpublic class OrderController {    public static final String PaymentSrv_URL = "http://localhost:8001";    @Autowired    private RestTemplate restTemplate;    @GetMapping("/consumer/payment/create")    public CommonResult create(Payment payment) {        return restTemplate.postForObject(PaymentSrv_URL + "/payment/create", payment, CommonResult.class);    }    @GetMapping("/consumer/payment/get/{id}")    public CommonResult getPayment(@PathVariable Long id) {        return restTemplate.getForObject(PaymentSrv_URL + "/payment/get/" + id, CommonResult.class, id);    }}
  • 工程重构

    由于子模块中有重复的entities部分,所以要进行工程重构

    1. 新建cloud-api-commons

    2. pom

      <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>        <dependency>            <groupId>cn.hutool</groupId>            <artifactId>hutool-all</artifactId>            <version>5.1.0</version>        </dependency></dependencies>
    3. entities

      • 主实体Payment

        package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class Payment implements Serializable {    private Long id;    private String serial;}
      • Json封装体CommonResult

        package com.wang.cloud.entities;@Data@AllArgsConstructor@NoArgsConstructorpublic class CommonResult<T> {    private Integer code;    private String message;    private T data;    public CommonResult(Integer code, String message) {        this(code, message, null);    }}
    4. maven命令clean、install

    5. 订单80和支付8001分别改造

      • 删除各自原先有过的entities文件夹

      • 修改各自模块的pom添加如下内容

        <dependency>    <groupId>com.wang.cloud</groupId>    <artifactId>cloud-api-commons</artifactId>    <version>1.0-SNAPSHOT</version></dependency>