• II第二章:(3)微服务案例


    一、前提

    约定 > 配置 > 编码

    二、IDEA新建project工作空间

    1、微服务cloud整体聚合父工程Project

    创建父工程步骤:

    (1)New Project

    (2)聚合总父工程名字

    (3)Maven选版本

    (4)工程名字

    (5)字符编码

    (6)注解生效激活

    (7)Java编译版本选JDK8

    (8)File Type 过滤

    2、父工程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>com.njf.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>
            <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>
     
        <!-- 子模块继承之后,提供作用:锁定版本+子modlue不用写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 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>

    3、Maven 细节复习

    (1)Maven中的DependencyManagement和Dependencies

    dependencyManagement

    Maven 使用dependencyManagement 元素来提供了一种管理依赖版本号的方式。 通常会在一个组织或者项目的最顶层的父POM 中看到dependencyManagement 元素。

    使用pom.xml 中的dependencyManagement 元素能让所有在子项目中引用一个依赖而不用显式的列出版本号。

    Maven 会沿着父子层次向上走,直到找到一个拥有dependencyManagement 元素的项目,然后它就会使用这个dependencyManagement 元素中指定的版本号。

    这样做的好处就是:如果有多个子项目都引用同一样依赖,则可以避免在每个使用的子项目里都声明一个版本号,这样当想升级或切换到另一个版本时,只需要在顶层父容器里更新,而不需要一个一个子项目的修改 ;另外如果某个子项目需要另外的一个版本,只需要声明version就可。

    • dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用的依赖。

    • 如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项,并且version和scope都读取自父pom;

    • 如果子项目中指定了版本号,那么会使用子项目中指定的jar版本。

    (2)maven中跳过单元测试

    配置方式:

    <build><!-- maven中跳过单元测试 -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

    IDEA工具支持(推荐)

    4、安装父工程

    父工程创建完成执行mvn:install将父工程发布到仓库方便子工程继承

    5、mysql驱动说明

    com.mysql.jdbc.Driver和mysql-connector-java 5一起用。

    com.mysql.cj.jdbc.Driver和mysql-connector-java 6 一起用。

    com.mysql.cj.jdbc.Driver是mysql-connector-java 6 中的特性,相比mysql-connector-java 5 多了一个时区:serverTimezone,把数据源配置的驱动改一下就好了

    org.gjt.mm.mysql.Driver是当时最好的MySQL JDBC,但不是MySQL公司的,然后MySQL将MM的JDBC驱动 收为官方的JDBC驱动,所以将驱动的package也改了,但还保留了org.gjt.mm.mysql.Driver这个路径的引用,也就是你使用新版的JDBC驱动时还可以通过这个来引用,打开下载的新版JDBC驱动的jar文件可以看到,只有一个文件的目录是org.gjt.mm.mysql,就是为了兼容而设计的。

    三、Rest微服务工程构建

    1、服务提供者

    cloud-provider-payment8001 微服务提供者支付Module模块 (1)建cloud-provider-payment8001

    (2)改 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">

        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.njf.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>

        <artifactId>cloud-provider-payment8001</artifactId>

        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>

        <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>
            <!--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>
            <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>

    </project>

    (3)写YML

    server:
      port: 8001

    spring:
      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:3308/cloud2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: root


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

    (4)主启动

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

    (5)业务类

    ① 建表 SQL

    CREATE TABLE `payment` (
      `id` bigint(20NOT NULL AUTO_INCREMENT COMMENT 'ID',
      `serial` varchar(200DEFAULT '',
      PRIMARY KEY (`id`)
    ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

    ② entities

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

    ③ vo Json封装体CommonResult

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

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

    }

    ④ dao 接口PaymentDao

    @Mapper
    public interface PaymentDao {
        public int create(Payment payment);

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

    }

    mybaits的映射文件PaymentMapper.xml 存放路径:src\main\resources\mapper\PaymentMapper.xml

    PaymentMapper.xml

    <?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.njf.springcloud.repository.PaymentDao">

        <resultMap id="BaseResultMap" type="com.njf.springcloud.entities.Payment">
            <id column="id" property="id" jdbcType="BIGINT"/>
            <result column="serial" property="serial" jdbcType="VARCHAR"/>
        </resultMap>

        <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
            INSERT INTO payment(SERIAL) VALUES(#{serial});
        </insert>

        <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap" >
            SELECT * FROM payment WHERE id=#{id};
        </select>
    </mapper>

    ⑤ service 接口PaymentService

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

        public Payment getPaymentById(Long id);
    }

    实现类:

    @Service
    public 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

    @RestController
    @Slf4j
    public class PaymentController {

        @Resource
        private PaymentService paymentService;

        @PostMapping(value = "/payment/create")
        public CommonResult create(@RequestBody Payment payment) {
            int result = paymentService.create(payment);
            log.info("*****插入操作返回结果:" + result);

            if(result > 0) {
                return new CommonResult(200,"插入数据库成功",result);
            } else {
                return new CommonResult(444,"插入数据库失败",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);
            }
        }
    }

    (6)测试

    浏览器发送 get 请求:

    http://localhost:8001/payment/get/1

    Postman 模拟 POST请求

    (7)小总结

    • 建module
    • 改POM
    • 写YML
    • 主启动
    • 业务类

    2、热部署Devtools

    (1)Adding devtools to your project

    <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

    下段配置我们粘贴进聚合父类总工程的pom.xml里
     
    <build>
        <finalName>你自己的工程名字</finalName>
        <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

    3、服务消费者

    cloud-consumer-order80 微服务消费者订单Module模块 (1)建cloud-consumer-order80

    (2)改 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">

        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.njf.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>

        <artifactId>cloud-consumer-order80</artifactId>

        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>

        <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>
    </project>

    (3)写YML


    server:
      port: 70

    (4)主启动

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

    (5)业务类 ① 使用上一个工程的 entities 和 vo 包中的实体类

    ② RestTemplate

    RestTemplate提供了多种便捷访问远程Http服务的方法, 是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。

    官网地址

    https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

    使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap, ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

    ③ config配置类

    @Configuration
    public class ApplicationContextConfig {

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

    ④ controller

    @RestController
    public class OrderController {

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

        @Autowired
        private RestTemplate restTemplate;

        @GetMapping(value = "/consumer/payment/create"//客户端用浏览器是get请求,但是底层实质发送post调用服务端8001
        public CommonResult create(Payment payment) {
            return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        }

        @GetMapping(value = "/consumer/payment/get/{id}")
        public CommonResult get(@PathVariable("id") Long id) {
            return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.classid);
        }
    }

    (6)测试 浏览器发送 GET 请求:

    http://localhost/consumer/payment/get/1

    不要忘记@RequestBody注解!

    4、工程重构

    (1)观察问题,系统中有重复部分,重构

    (2)新建 cloud-api-commons (3)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">

        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.njf.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>

        <artifactId>cloud-api-commons</artifactId>

        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>

        <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>

    </project>

    (4)把 entities和vo包移动到该模块中

    (5)maven 命令 clean install

    (6)订单80和支付8001分别改造,删除各自的原先有过的entities文件夹,再加入 cloud-api-commons 模块

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

    5、工程样图

  • 相关阅读:
    lampp、xampp安装文档
    tomcat下配置https方式
    1.6:怎么学习Linux
    1.5:linux的应用领域
    1.3:linux的优点和缺点
    1.4:Linux发行版本详解
    1.2:liunx和unix的区别
    1.1:Linux系统简介
    mysql中获取表名&字段名的查询语句
    kettle组件-输出
  • 原文地址:https://www.cnblogs.com/niujifei/p/16215376.html
Copyright © 2020-2023  润新知