2、微服务架构编码构建初始步骤和订单模块构建(个人的学习笔记)

1、此次学习所用技术相关的版本

  • SpringCloudHoxton.SR1
  • SpringBoot2.2.2.RELEASE
  • SpringCloud alibaba2.1.0.RELEASE
  • JavaJava8
  • Maven3.5及以上
  • Mysql5.7及以上

2、和之前相比,SpringCloud的升级

在这里插入图片描述

3、微服务架构编码构建( 约定 > 配置 > 编码)

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

父工程的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.springcloud</groupId>
    <artifactId>cloud2020</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging><!-- 这里添加,注意不是jar或war -->

    <!-- 统一管理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.49</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>
</project>

02、复习dependencyManagement和dependencies

  • Maven中使用dependencyManagement元素来提供了一种管理依赖版本号的方式。
  • 通常会在一个组织或者项目中的最顶层的父pom文件中看到dependencyManagement元素,使用了dependencyManagement元素后,可以让所有的子项目在引用相同依赖时不用列出版本号
  • Maven会沿着父子层次向上走,直到找到一个拥有dependencyManagement元素的项目,然后它就会使用这个
    dependencyManagement元素中指定的版本号。

在父项目中引用格式

	<dependencyManagement>
	    <dependencies>
	        <dependency>
	        <groupId>mysq1</groupId>
	        <artifactId>mysql-connector-java</artifactId>
	        <version>5.1.2</version>
	        </dependency>
	    <dependencies>
	</dependencyManagement>

父项目中使用了dependencyManagement后,子项目添加依赖时,就不需要指定版本号了

	    <dependencies>
	        <dependency>
	        <groupId>mysq1</groupId>
	        <artifactId>mysql-connector-java</artifactId>
	        </dependency>
	    <dependencies>

父项目中使用dependencyManagement元素的好处

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

  • dependencyManagement元素的作用只是声明依赖,并不实现引入,所以当子项目需要声明需要用的依赖。
  • 如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中引用了该依赖项,并且没有指定具体的版本,才会从父项目中继承该该依赖,并且versionscope都读取自父工程中的pom文件。
  • 如果子项目中的依赖指定了版本号,那么会使用子项目中指定的jar版本,不会继承父项目中的依赖。

3.2、Rest微服务工程构建(微服务提供者支付Module模块)

那么如何搭建微服务模块呢?

  • module
  • pom文件
  • YML
  • 主启动
  • 业务类

创建微服务提供者支付Module模块

1、创建子项目:名为cloud-provider-payment8001的Maven工程
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.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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</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文件——application.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驱动包
    url: jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: Seeyon123456

mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
  type-aliases-package: com.springclond.study.entity  #所有Entity别名类所在的包·

4、编写主启动类

package com.spring.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

5、编写业务类

5.1、建表sql

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

5.2、创建实体类

package com.spring.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

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

JSON封装体CommonResult,这个是模拟一个消息体,意在告诉前端一个状态(是否成功),是否继续向下操作

package com.spring.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 返回前端一个通用的json实体串
 */
@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);
    }
}

5.3、dao层

package com.spring.dao;

import com.spring.entity.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface PaymentDao {

    /**
     * 创建
     *
     * @param payment
     * @return
     */
    public int create(Payment payment);

    /**
     * 根据id获取实体对象
     *
     * @param id
     * @return
     */
    public Payment getPaymentById(@Param("id") Long id);
}

5.4、dao层(MyBatis映射文件PaymentMapper.xml,路径:resources/mapper/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.spring.study.dao.PaymentDao">

    <resultMap id="BaseResultMap" type="com.spring.study.entity.Payment">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <id 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>

5.5、service层和实现类

package com.spring.study.service;

import com.spring.study.entity.Payment;
import org.apache.ibatis.annotations.Param;

public interface PaymentService {
    /**
     * 创建
     *
     * @param payment
     * @return
     */
    public int create(Payment payment);

    /**
     * 根据id获取实体对象
     *
     * @param id
     * @return
     */
    public Payment getPaymentById(@Param("id") Long id);
}

实现类

package com.spring.study.service.impl;

import com.spring.study.dao.PaymentDao;
import com.spring.study.entity.Payment;
import com.spring.study.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private PaymentDao paymentDao;

    /**
     * 创建
     *
     * @param payment
     * @return
     */
    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }
}

5.6、controller层

package com.spring.study.controller;

import com.spring.study.entity.CommonResult;
import com.spring.study.entity.Payment;
import com.spring.study.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public 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(404, "插入失败", result);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult 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(404, "没有对应记录" + id, null);
        }
    }
}

测试接口是否正确

这里测试我用的是PostMan工具,因为浏览器不支持PostMapping请求

  • 测试创建
    在这里插入图片描述

  • 测试根据id查询
    在这里插入图片描述

3.3、Rest微服务工程构建(微服务消费者订单Module模块)

建Model模块cloud-consumer-order80

修改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.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>

写yml文件

server:
  port: 80

主启动

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

编写业务类

  • 实体类在这里也是需要,并且和提供者的是一样的
  • Payment实体对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private Long id;
    private String serial;
}
/**
 * 返回前端一个通用的json实体串
 */
@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);
    }
}

controller层

  • 这里需要用到restTemplate,实现了订单微服务和支付微服务之间的横向调用,RestTemplate提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集。这里就需要配置resdisTemplate

那么应该如何使用呢?

  • 使用restTemplate访问restful接口非常的简单粗暴无脑。

  • 参数(url, requestMap, ResponseBean.class)这三个参数分别代表, REST请求地址、请求参数、HTTP响应转换被转换成的对象类型

  • 新建config目录

@Configuration
public class ApplicationContextConfig {

    @Bean //依赖注入
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  • 支付微服务的controller
@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(@RequestBody Payment payment) {
        //写操作用post请求postForObject
        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);
    }
}

测试消费者订单模块

  • 查询结果
    在这里插入图片描述
  • 创建结果

注意:这块创建的方法中,实体之前要加@RequestBody
在这里插入图片描述

3.4、工程重构

  • 为什么要重构?我们可以观察到在两个微服务中存在一个entity,而且内容是一模一样的,属于重复代码。需要重新构建。

  • 如何重构?我们可以将重复的代码提取到一个微服务中,供其他服务调用。

1、新建一个module,工程名为cloud-api-commons

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.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>
  • cloud-consumer-order80cloud-provider-payment8001两工程的公有entitiy包移至cloud-api-commons工程下。

  • 然后执行maven cleaninstall 操作。cloud-api-commons工程,以供给cloud-consumer-order80cloud-provider-payment8001两工程调用。

3、将微服务提供者和微服务消费者中的entity删除,并引入cloud-api-commons依赖

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

学习视频:网址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值