第二章:微服务架构构建

第二章:微服务架构构建

2.1:IDEA新建project工作空间

  • 父工程步骤

    1. New Project
      第二章:微服务架构构建_第1张图片

    2. 聚合总父工程名字
      第二章:微服务架构构建_第2张图片

    3. Maven版本选择
      第二章:微服务架构构建_第3张图片

    4. 字符编码
      第二章:微服务架构构建_第4张图片

    5. 注解生效激活
      第二章:微服务架构构建_第5张图片

    6. Java编译版本选择8
      第二章:微服务架构构建_第6张图片

  • 父工程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.0modelVersion>
    
        <groupId>com.wang.cloudgroupId>
        <artifactId>cloud2022artifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>pompackaging>
    
        <properties>
            <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
            <maven.compiler.source>1.8maven.compiler.source>
            <maven.compiler.target>1.8maven.compiler.target>
            <junit.version>4.12junit.version>
            <log4j.version>1.2.17log4j.version>
            <lombok.version>1.16.18lombok.version>
            <mysql.version>8.0.19mysql.version>
            <druid.version>1.1.16druid.version>
            <spring.boot.version>2.2.2.RELEASEspring.boot.version>
            <spring.cloud.version>Hoxton.SR1spring.cloud.version>
            <spring.cloud.alibaba.version>2.1.0.RELEASEspring.cloud.alibaba.version>
            <mybatis.spring.boot.version>1.3.0mybatis.spring.boot.version>
        properties>
    
        <dependencyManagement>
            <dependencies>
                
                <dependency>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-dependenciesartifactId>
                    <version>${spring.boot.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                
                <dependency>
                    <groupId>org.springframework.cloudgroupId>
                    <artifactId>spring-cloud-dependenciesartifactId>
                    <version>${spring.cloud.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                
                <dependency>
                    <groupId>com.alibaba.cloudgroupId>
                    <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                    <version>${spring.cloud.alibaba.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                <dependency>
                    <groupId>mysqlgroupId>
                    <artifactId>mysql-connector-javaartifactId>
                    <version>${mysql.version}version>
                dependency>
                <dependency>
                    <groupId>com.alibabagroupId>
                    <artifactId>druidartifactId>
                    <version>${druid.version}version>
                dependency>
                <dependency>
                    <groupId>org.projectlombokgroupId>
                    <artifactId>lombokartifactId>
                dependency>
            dependencies>
        dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <configuration>
                        <fork>truefork>
                        <addResources>trueaddResources>
                    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,然后直接下一步
        第二章:微服务架构构建_第7张图片

      • 模块命名
        第二章:微服务架构构建_第8张图片

    2. 改POM

      <dependencies>
              <dependency>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-starter-webartifactId>
              dependency>
              <dependency>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-starter-actuatorartifactId>
              dependency>
              <dependency>
                  <groupId>org.mybatis.spring.bootgroupId>
                  <artifactId>mybatis-spring-boot-starterartifactId>
              dependency>
              <dependency>
                  <groupId>com.alibabagroupId>
                  <artifactId>druid-spring-boot-starterartifactId>
                  <version>1.1.10version>
              dependency>
              
              <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
              dependency>
              
              <dependency>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-starter-jdbcartifactId>
              dependency>
              <dependency>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-devtoolsartifactId>
                  <scope>runtimescope>
                  <optional>trueoptional>
              dependency>
              <dependency>
                  <groupId>org.projectlombokgroupId>
                  <artifactId>lombokartifactId>
                  <optional>trueoptional>
              dependency>
              <dependency>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-starter-testartifactId>
                  <scope>testscope>
              dependency>
      dependencies>
      
    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:3306/db2019
          username: root
          password: root
      
      mybatis:
        mapperLocations: classpath:mapper/*.xml
        type-aliases-package: com.wang.cloud.entities    # 所有Entity别名类所在包
      
    4. 主启动

      package com.wang.cloud;
      
      @SpringBootApplication
      public 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
          @NoArgsConstructor
          public class payment implements Serializable {
              private Long id;
              private String serial;
          }
          
        2. Json封装体CommonResult

          package com.wang.cloud.entities;
          
          @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

        1. 接口PaymentDao

          package com.wang.cloud.dao;
          
          @Mapper
          public 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;
          
          @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

        package com.wang.cloud.controller;
        
        @RestController
        @Slf4j
        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(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.bootgroupId>
          <artifactId>spring-boot-devtoolsartifactId>
          <scope>runtimescope>
          <optional>trueoptional>
      dependency>
      
    2. Adding plugin to your pom.xml

      注:放在父项目里,如果上方已经引入,此处可以不引入
      <build>
          <plugins>
              <plugin>
                  <groupId>org.springframework.bootgroupId>
                  <artifactId>spring-boot-maven-pluginartifactId>
                  <configuration>
                      <fork>truefork>
                      <addResources>trueaddResources>
                  configuration>
              plugin>
          plugins>
      build>
      
    3. Enabling automatic build
      第二章:微服务架构构建_第9张图片

    4. update the value of
      第二章:微服务架构构建_第10张图片
      第二章:微服务架构构建_第11张图片

    5. 重启IDEA

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

    1. cloud-consumer-order80模块

    2. pom

      <dependencies>
          <dependency>
              <groupId>org.springframework.bootgroupId>
              <artifactId>spring-boot-starter-webartifactId>
          dependency>
          <dependency>
              <groupId>org.springframework.bootgroupId>
              <artifactId>spring-boot-starter-actuatorartifactId>
          dependency>
      
          <dependency>
              <groupId>org.springframework.bootgroupId>
              <artifactId>spring-boot-devtoolsartifactId>
              <scope>runtimescope>
              <optional>trueoptional>
          dependency>
          <dependency>
              <groupId>org.projectlombokgroupId>
              <artifactId>lombokartifactId>
              <optional>trueoptional>
          dependency>
          <dependency>
              <groupId>org.springframework.bootgroupId>
              <artifactId>spring-boot-starter-testartifactId>
              <scope>testscope>
          dependency>
      dependencies>
      
    3. yml

      server:
        port: 80
      
    4. 主启动

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

      • entities

        1. 主实体Payment

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

          package com.wang.cloud.entities;
          
          @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);
              }
          }
          
      • config配置类

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

        package com.wang.cloud.controller;
        
        @RestController
        public 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.bootgroupId>
                  <artifactId>spring-boot-devtoolsartifactId>
                  <scope>runtimescope>
                  <optional>trueoptional>
              dependency>
              <dependency>
                  <groupId>org.projectlombokgroupId>
                  <artifactId>lombokartifactId>
                  <optional>trueoptional>
              dependency>
              <dependency>
                  <groupId>cn.hutoolgroupId>
                  <artifactId>hutool-allartifactId>
                  <version>5.1.0version>
              dependency>
      dependencies>
      
    3. entities

      • 主实体Payment

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

        package com.wang.cloud.entities;
        
        @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);
            }
        }
        
    4. maven命令clean、install

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

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

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

        <dependency>
            <groupId>com.wang.cloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        

你可能感兴趣的:(SpringCloud,java,spring,cloud)