SpringCloud 02 - 微服务架构编码 构建

SpringCloud 01 - 基础理论


1. IDEA 新建 project 工作空间

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

父工程步骤

① New Project

② 字符编码

③注解生效激活

④Java 编译版本选 8

⑤ File Type 过滤(可选)

这个看个人习惯了,设不设都行。我就是看着难受哈哈哈...

设之前是这样的:

设之后:

2)父工程POM

这个 src 删掉就行,反正没啥用,因为待会会建 module..

<?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.janet.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.17</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.verison>1.3.0</mybatis.spring.boot.verison>
  </properties>

  <!--子模块继承后,提供作用:锁定版本+子module不用groupId和version-->
  <dependencyManagement>
    <dependencies>
      <!--springboot 2.2.2-->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring.boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--Spring cloud Hoxton.SR1-->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring.cloud.version}</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>${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-spring-boot-starter</artifactId>
        <version>${druid.version}</version>
      </dependency>

      <!-- mybatis-springboot整合 -->
      <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis.spring.boot.verison}</version>
      </dependency>

      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
      </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 工程落地细节

① Maven 中的 DependencyManagement 和 Dependencies

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

使用 pom.xml 中的 DependencyManagement  元素能让所有在子项目中引入一个依赖而不显式地列出版本号。Maven 会沿着父子层次走,直到找到一个拥有 DependencyManagement 元素的项目,然后它就会使用这个 DependencyManagement  元素中指定的版本号。

例如在父项目里:

然后在子项目里就可以添加 mysql-connection 时就可以不指定版本号,例如:

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

  • DependencyManagement  里只是声明依赖,并不实现引入,因此子项目需要显式的声明需要用的依赖。
  • 如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中写入了该依赖项,并且没有指定具体版本,才会从父项目中继承,并且 version 和 scope 都读自父 pom。
  • 如果子项目中指定了版本号,那么就会使用子项目中指定的 jar 版本。

② maven 中跳过单元测试

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

2. Rest 微服务工程构建

1)Cloud-provider-payment8001 微服务提供者Module模块

① 建module(cloud-provider-payment8001

创建完成后回到父工程查看pom文件变化

② 改POM(Cloud-provider-payment8001 的 pom.xml:

<dependencies>
        <!--web启动器 和下面的监控几乎同时出现-->
        <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>
        <!--SpringBoot整合 mybatis启动器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <!--mysql驱动-->
        <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>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <optional>true</optional>
        </dependency>
        <!--SpringBoot测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

③ 写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 #数据库驱动包
    url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 1234

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.janet.springcloud.entities  #所有entity别名所在包

④主启动类

package com.janet.springcloud;

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

/**
 * @Description PaymentMain8001 主启动类
 * @Date 2020/4/29
 * @Author Janet
 */
@SpringBootApplication
public class PaymentMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class, args);
    }
}

⑤ 业务类

  • 建表sql (建表之前先建一个数据库,我的叫 cloud)
CREATE TABLE `payment` (
	`id` BIGINT (20) NOT NULL AUTO_INCREMENT COMMENT '主键',
	`serial` VARCHAR (200) CHARACTER
SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '支付流水号',
 PRIMARY KEY (`id`) USING BTREE
) ENGINE = INNODB CHARACTER
SET = utf8 COLLATE = utf8_general_ci COMMENT = '支付表' ROW_FORMAT = Dynamic;
  • entities

主实体 Payment:

package com.janet.springcloud.entities;

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

/**
 * @Description TODO
 * @Date 2020/4/29
 * @Author Janet
 *
 *  加上序列化,后面分布式部署会用得到
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    
    //主键
    private Long id;  // 建表的时候用的 BIGINT

    //支付流水号
    private String  serial;

}

使用上面的注解注意一下有没有安装 lombok 插件哦!

Json 封装体 CommonResult:

package com.janet.springcloud.entities;

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

/**
 * @Description Json 封装体
 * @Date 2020/4/29
 * @Author Janet
 */

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

    // data 有时候可能为空 (全参构造方法上面的注解已经实现了)
    public CommonResult(Integer code, String message){
        this(code,message,null);
    }

}
  • dao

        接口 PaymentDao

package com.janet.springcloud.dao;

import com.janet.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * @Description TODO
 * @Date 2020/4/29
 * @Author Janet
 */
@Mapper
public interface PaymentDao {
    public int create(Payment payment);

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

}

mybatis 的映射文件PaymentMapper.xml(路径:src\main\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.janet.springcloud.dao.PaymentDao">

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

    <insert id="create" parameterType="com.janet.springcloud.entities.Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values(#{serial});
    </insert>
    
    <select id="getPaymentById" parameterType="long" resultMap="BaseResultMap">
        select id, serial from payment where id = #{id};
    </select>
    
</mapper>
  • service

接口 PaymentService

package com.janet.springcloud.service;

import com.janet.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Param;

/**
 * @Description TODO
 * @Date 2020/4/29
 * @Author Janet
 */
public interface PaymentService {
    public int create(Payment payment);

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

实现类 PaymentServiceImpl

package com.janet.springcloud.service.impl;

import com.janet.springcloud.dao.PaymentDao;
import com.janet.springcloud.entities.Payment;
import com.janet.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Date 2020/4/29
 * @Author Janet
 */
@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired
    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.janet.springcloud.controller;

import com.janet.springcloud.entities.CommonResult;
import com.janet.springcloud.entities.Payment;
import com.janet.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description TODO
 * @Date 2020/4/29
 * @Author Janet
 */
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping(value = "/payment/create")
    public CommonResult<Integer> 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> create(@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);

    }
}

 ( 注意:@RequestBody 注解别忘了加 )

⑥ 测试

这里的插入测试我用的 postman:

开启 Run DashBoard

(一般会自己出来,如果不会的话再修改)

① 打开项目本地路径:

② 通过修改 idea 的workspace.xml

<component name="RunDashboard">
    <option name="configurationTypes">
        <set>
            <option value="SpringBootApplicationConfigurationType" />
        </set>
    </option>
</component>

重启 idea 

2)热部署Devtools

(这玩意只能在开发环境用哈,生产环境整这个那就太影响效率了。)

① Adding devtools to your project(在刚刚 Cloud-provider-payment8001 的 pom.xml 文件中其实已经加过了,就不用重复了)

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

②Adding plugin to your pom.xml(上面的父 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>

③ Enabling automatic build

④Update the value of

快捷键 Ctrl + Shift + Alt + /

把这两个勾上:

⑤ 重启idea

重启完了之后热部署就成功了,修改代码就会自动编译(亲测,好用!)

对了,到现在为止,这是到目前为止的项目:

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

① 建 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.janet.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

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

    <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>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

</project>

③ application.yml

server:
  port: 80

④ 主启动 OrderMain80 

package com.janet.springcloud;

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

/**
 * @author janet
 * @date 2020/4/29
 */
@SpringBootApplication
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class, args);
    }
}

⑤ 业务类

  • entites

把 8001 module 里面的两个实体类复制到 80 module 中:

RestTemplate:

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

官方地址:RestTemplate (Spring Framework 5.2.2.RELEASE API)

使用:

使用 restTemplate 访问 restful 接口:(url, requestMap, ResponseBean.class)这三个参数分别代表 Rest 请求地址、请求参数、HTTP 响应转换成的对象类型。

因为要使用 RestTemplate,所以要写一个config配置类:

package com.janet.springcloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author Janet
 * @date 2020/4/29
 */
@Configuration
public class ApplicationContextConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}
  • controller
package com.janet.springcloud.controller;

import com.janet.springcloud.entities.CommonResult;
import com.janet.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author Janet
 * @date 2020/4/29
 */
@RestController
@Slf4j
public class OrderController {
    private final static String PAYMENT_URL = "http://localhost:8001"; //暂时写死,后面再改

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")  //只能发 get 请求
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

}

⑥ 测试

启动 8001 和 80 两个 module,测试 80:

不要忘记在 PaymentController 的 create 方法中添加 @RequestBody 注解,不然插入的数据是空的:

4)工程重构

当前项目:

可以看到两个 module 中有相同的 entity 类,所以需要提出来。

① 新建  cloud-api-common module

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

③ entties (把前两个 module 中其中一个的 entities 复制过来,然后那两个 module 的 entities 包删掉)

④ maven命令clean install

⑤ 订单80和支付8001分别改造

  • 删除各自的原先的 entities 文件夹
  • 各自粘贴 POM 内容
        <!--本项目的 common 模块-->
        <dependency>
            <groupId>com.janet.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>

启动项目,再测试一遍看看有没有错的--

目前的项目结构:


SpringCloud 03 - Eureka

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值