IntelliJ IDEA 2018.3 创建 Maven 多模块(Module)项目+负载均衡【持续更新】

2019年08月05日 17:58 · 阅读(6643) ·

参考

Java 项目学习笔记

IntelliJ IDEA创建maven多模块项目

IntelliJ IDEA知识集锦

springcloud(二):注册中心Eureka

springcloud(三):服务提供与调用

10.Spring Cloud-服务注册与发现(Eureka)

pom.xml 中定义和使用变量

开发环境

名称 版本
操作系统 Windows 10 X64
JDK JDK1.8(jdk-8u151-windows-x64)
IntelliJ IDEA IntelliJ IDEA 2018.3
Maven Maven 3.6.0

测试表-t_rbt_test

位于本地 MySql 数据库 luoma_test

  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS = 0;
  3. -- ----------------------------
  4. -- Table structure for t_rbt_test
  5. -- ----------------------------
  6. DROP TABLE IF EXISTS `t_rbt_test`;
  7. CREATE TABLE `t_rbt_test` (
  8. `id` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '主键',
  9. `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '名称',
  10. `version` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '版本号',
  11. `create_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
  12. `create_time` timestamp(0) NULL DEFAULT NULL COMMENT '创建时间',
  13. `update_by` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '修改人',
  14. `update_time` timestamp(0) NULL DEFAULT NULL COMMENT '修改时间',
  15. `is_delete` int(1) NULL DEFAULT NULL COMMENT '是否删除',
  16. `biz_time` timestamp(0) NULL DEFAULT NULL COMMENT '系统时间戳',
  17. PRIMARY KEY (`id`) USING BTREE
  18. ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
  19. SET FOREIGN_KEY_CHECKS = 1;

组件引用说明

由于篇幅有限,加上侧重点的问题。本文中引用的组件请参考

常用 Maven 组件 pom 配置,import 及使用

项目源代码

见附件

创建父模块-test-invoice-cloud

文件-New-项目

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

依次补全下面的信息,点击 下一个

节点 描述
groupId 代表组织和整个项目的唯一标志,是项目组织唯一的知标识符,实际对应 JAVA 的包的结构
artifactId 项目的唯一的标识符,实际对应项目的名称
version 用于说明目前项目的版本

输入项目名称 test-invoice-cloud ,我们主要是在这个项目下创建我们的子模块

这样我们就创建好了一个普通项目,因为该项目是作为一个解决方案存在的,可以直接删除 src 文件夹

创建好的项目如下

项目文件名称及含义

目录/文件 含义
.idea 创建项目的时候自动创建一个 .idea 的项目配置目录来保存项目的配置信息。这是默认选项。 子目录包含一系列XML文件,包括:compiler.xml、encodings.xml、modules.xml等。这些文件记录工程本身的核心信息,包括:模块组件的名称和位置、编译器设置等,可以存放到VCS。一个例外是workspace.xml,该文件存储个人设置(例如窗口位置)以及其它附属于开发环境的信息,不应该存放到VCS
pom.xml Maven 项目配置文件。POM( Project Object Model,项目对象模型 ) 是 Maven 工程的基本工作单元,是一个XML文件,包含了项目的基本信息,用于描述项目如何构建,声明项目依赖,等等。执行任务或目标时,Maven 会在当前目录中查找 POM。它读取 POM,获取所需的配置信息,然后执行目标。
.iml 模块是工程中一个可以独立编译、运行、调试、测试的单元。模块的配置信息默认存放在其内容根目录(Content root folder)下的 .iml 文件中,该文件一般存放到VCS。

设置 Maven 引用地址

注意,这里的设置是必须的。相关组件的下载就需要这里的配置。

设置 Maven 引用地址

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <!--父级:Spring Boot-->
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <!--<version>2.0.1.RELEASE</version>-->
  10. <!--<version>2.0.3.RELEASE</version>--><!--解决循环引用对象问题mybatis https://github.com/heikehuan/springboot-multiple-dataSources/issues/2-->
  11. <version>2.0.9.RELEASE</version>
  12. </parent>
  13. <modelVersion>4.0.0</modelVersion>
  14. <groupId>com-test-invoice</groupId>
  15. <artifactId>test-invoice-cloud</artifactId>
  16. <version>1.0-SNAPSHOT</version>
  17. <name>test-invoice-cloud</name>
  18. <packaging>pom</packaging>
  19. <modules>
  20. <module>test-invoice-common</module>
  21. <module>test-invoice-contract</module>
  22. <module>test-invoice-service</module>
  23. <module>test-invoice-web</module>
  24. <module>test-invoice-eureka</module>
  25. </modules>
  26. <properties>
  27. <springCloud.version>Finchley.RELEASE</springCloud.version>
  28. <fastjson.version>1.2.38</fastjson.version>
  29. <swagger.version>2.7.0</swagger.version>
  30. <lombok.version>1.18.6</lombok.version>
  31. <HikariCP.version>3.3.1</HikariCP.version>
  32. <mybatis-plus-spring-boot-starter.version>3.1.0</mybatis-plus-spring-boot-starter.version>
  33. <swagger-ui.version>2.7.0</swagger-ui.version>
  34. </properties>
  35. <!--Spring Cloud 版本序列配置-->
  36. <dependencyManagement>
  37. <dependencies>
  38. <dependency>
  39. <groupId>org.springframework.cloud</groupId>
  40. <artifactId>spring-cloud-dependencies</artifactId>
  41. <version>${springCloud.version}</version>
  42. <type>pom</type>
  43. <scope>import</scope>
  44. <exclusions>
  45. <exclusion>
  46. <groupId>redis.clients</groupId>
  47. <artifactId>jedis</artifactId>
  48. </exclusion>
  49. </exclusions>
  50. </dependency>
  51. </dependencies>
  52. </dependencyManagement>
  53. <dependencies>
  54. <!--Spring Boot 执行器组件-->
  55. <dependency>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-starter-actuator</artifactId>
  58. </dependency>
  59. <!--Spring Cloud 基础-->
  60. <dependency>
  61. <groupId>org.springframework.cloud</groupId>
  62. <artifactId>spring-cloud-starter</artifactId>
  63. </dependency>
  64. <!--Spring Cloud 服务注册组件-->
  65. <dependency>
  66. <groupId>org.springframework.cloud</groupId>
  67. <!--此处的依赖是SpringBoot2.0以后专用的,如果您使用的SpringBoot版本低于2.0请使用spring-cloud-starter-eureka-server-->
  68. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  69. </dependency>
  70. <!--Spring Boot 测试组件-->
  71. <dependency>
  72. <groupId>org.springframework.boot</groupId>
  73. <artifactId>spring-boot-starter-test</artifactId>
  74. <scope>test</scope>
  75. </dependency>
  76. <!--Spring Boot Web组件-->
  77. <dependency>
  78. <groupId>org.springframework.boot</groupId>
  79. <artifactId>spring-boot-starter-web</artifactId>
  80. <!-- 从依赖信息里移除 Tomcat配置 -->
  81. <exclusions>
  82. <exclusion>
  83. <groupId>org.springframework.boot</groupId>
  84. <artifactId>spring-boot-starter-tomcat</artifactId>
  85. </exclusion>
  86. </exclusions>
  87. </dependency>
  88. <!-- 参数校验信息 -->
  89. <dependency>
  90. <groupId>org.springframework.boot</groupId>
  91. <artifactId>spring-boot-starter-validation</artifactId>
  92. </dependency>
  93. <!-- 添加 Undertow依赖 start-->
  94. <dependency>
  95. <groupId>org.springframework.boot</groupId>
  96. <artifactId>spring-boot-starter-undertow</artifactId>
  97. </dependency>
  98. <!-- 添加 Undertow依赖 end-->
  99. <!-- spring aop start -->
  100. <dependency>
  101. <groupId>org.springframework.boot</groupId>
  102. <artifactId>spring-boot-starter-aop</artifactId>
  103. </dependency>
  104. <!-- spring aop end -->
  105. <!--lombok start-->
  106. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  107. <dependency>
  108. <groupId>org.projectlombok</groupId>
  109. <artifactId>lombok</artifactId>
  110. <version>${lombok.version}</version>
  111. </dependency>
  112. <!--lombok end-->
  113. <!--fastJson start-->
  114. <!--Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库-->
  115. <dependency>
  116. <groupId>com.alibaba</groupId>
  117. <artifactId>fastjson</artifactId>
  118. <version>${fastjson.version}</version>
  119. </dependency>
  120. <!--fastJson end-->
  121. <!--swagger start-->
  122. <!--springfox是通过注解的形式自动生成API文档,利用它,可以很方便的书写restful API,swagger主要用于展示springfox生成的API文档-->
  123. <dependency>
  124. <groupId>io.springfox</groupId>
  125. <artifactId>springfox-swagger2</artifactId>
  126. <version>${swagger.version}</version>
  127. </dependency>
  128. <!--swagger end-->
  129. </dependencies>
  130. <!--注意:这里必须要添加,否则各种依赖有问题-->
  131. <repositories>
  132. <repository>
  133. <id>spring-milestones</id>
  134. <name>Spring Milestones</name>
  135. <url>https://repo.spring.io/libs-milestone</url>
  136. <snapshots>
  137. <enabled>false</enabled>
  138. </snapshots>
  139. </repository>
  140. </repositories>
  141. <build>
  142. <plugins>
  143. <plugin>
  144. <!-- 指定maven编译的jdk版本,如果不指定,maven3默认用jdk 1.5 maven2默认用jdk1.3 -->
  145. <groupId>org.apache.maven.plugins</groupId>
  146. <artifactId>maven-compiler-plugin</artifactId>
  147. <version>3.1</version>
  148. <configuration>
  149. <!-- 一般而言,target与source是保持一致的,但是,有时候为了让程序能在其他版本的jdk中运行(对于低版本目标jdk,源代码中不能使用低版本jdk中不支持的语法),会存在target不同于source的情况 -->
  150. <source>1.8</source> <!-- 源代码使用的JDK版本 -->
  151. <target>1.8</target> <!-- 需要生成的目标class文件的编译版本 -->
  152. <encoding>UTF-8</encoding><!-- 字符集编码 -->
  153. <!--<skipTests>true</skipTests>&lt;!&ndash; 跳过测试 &ndash;&gt;
  154. <verbose>true</verbose>
  155. <showWarnings>true</showWarnings>
  156. <fork>true</fork>&lt;!&ndash; 要使compilerVersion标签生效,还需要将fork设为true,用于明确表示编译版本配置的可用 &ndash;&gt;
  157. <executable>&lt;!&ndash; path-to-javac &ndash;&gt;</executable>&lt;!&ndash; 使用指定的javac命令,例如:<executable>${JAVA_1_4_HOME}/bin/javac</executable> &ndash;&gt;
  158. <compilerVersion>1.3</compilerVersion>&lt;!&ndash; 指定插件将使用的编译器的版本 &ndash;&gt;
  159. <meminitial>128m</meminitial>&lt;!&ndash; 编译器使用的初始内存 &ndash;&gt;
  160. <maxmem>512m</maxmem>&lt;!&ndash; 编译器使用的最大内存 &ndash;&gt;
  161. <compilerArgument>-verbose -bootclasspath ${java.home}\lib\rt.jar</compilerArgument>--><!-- 这个选项用来传递编译器自身不包含但是却支持的参数选项 -->
  162. </configuration>
  163. </plugin>
  164. <plugin>
  165. <groupId>org.sonarsource.scanner.maven</groupId>
  166. <artifactId>sonar-maven-plugin</artifactId>
  167. <version>3.5.0.1254</version>
  168. </plugin>
  169. </plugins>
  170. </build>
  171. </project>

创建子模块-test-invoice-eureka

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-eureka

模块名称 test-invoice-eureka

创建类和文件

模块简介

这个模块对应的是 Eureka Server

Eureka Server 提供服务注册服务,各个节点启动后,会在 Eureka Server 中进行注册,这样 EurekaServer 中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。

这里只是作为项目中的一个模块,详细的了解可参考下面的内容

springcloud(二):注册中心Eureka

springcloud(三):服务提供与调用

10.Spring Cloud-服务注册与发现(Eureka)

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-eureka</artifactId>
  12. <name>test-invoice-eureka</name>
  13. <properties>
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-netflix-eureka-server</artifactId>
  20. <version>2.0.0.M7</version>
  21. <scope>compile</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>junit</groupId>
  25. <artifactId>junit</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. </dependencies>
  29. <build>
  30. <finalName>${project.artifactId}</finalName>
  31. <plugins>
  32. <plugin>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-maven-plugin</artifactId>
  35. </plugin>
  36. </plugins>
  37. <resources>
  38. <resource>
  39. <directory>src/main/resources</directory>
  40. <includes>
  41. <include>**/*</include>
  42. </includes>
  43. </resource>
  44. </resources>
  45. </build>
  46. </project>

yml

application.yml

  1. spring:
  2. # 节点1的标签
  3. profiles:
  4. active: dev
  5. activiti:
  6. check-process-definitions: false #校验流程文件,默认校验resources下的processes文件夹里的流程文件
  7. # 服务名保持一致
  8. application:
  9. name: eureka-ha

application-dev.yml

  1. server:
  2. port: 8772
  3. # 配置Eureka Server 信息
  4. eureka:
  5. client:
  6. # 表示是否将自己注册到Eureka Server,不进行注册(当服务注册中心是单点而非高可用时的配置方式)
  7. registerWithEureka: false
  8. # 表示是否从Eureka Server获取注册信息,不获取注册信息(当服务注册中心是单点而非高可用时的配置方式)
  9. fetchRegistry: false
  10. #设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://localhost:8761/eureka ;多个地址可使用 , 分隔
  11. service-url:
  12. defaultZone: http://localhost:${server.port}/eureka/
  13. # 自定义实例编号
  14. instance:
  15. instance-id: ${spring.application.name}:${server.port}
  16. # 配置使用主机名注册服务
  17. #hostname: peer1
  18. # 优先使用IP地址方式进行注册服务
  19. prefer-ip-address: true
  20. # 配置使用指定IP
  21. ip-address: 127.0.0.1

入口类-EurekaHaApplication

  1. package com.test.eurekaha;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
  5. import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
  6. import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
  7. import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
  8. import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
  9. /**
  10. * EurekaHaApplication
  11. *
  12. * @author:
  13. * @version:
  14. * @date: 2019-08-13 15:26
  15. */
  16. //排除掉数据库配置项目
  17. @SpringBootApplication( exclude = {
  18. DataSourceAutoConfiguration.class,
  19. DataSourceTransactionManagerAutoConfiguration.class,
  20. RedisAutoConfiguration.class,
  21. RedisRepositoriesAutoConfiguration.class
  22. })
  23. @EnableEurekaServer
  24. public class EurekaHaApplication {
  25. public static void main(String[] args) {
  26. SpringApplication.run(EurekaHaApplication.class, args);
  27. }
  28. }

测试

创建成功后,启动项目,访问 http://localhost:8772/

创建子模块-test-invoice-common

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-common

模块名称 test-invoice-common

模块简介

test-invoice-common 这个模块主要是创建一些公共类,实体提供给其它模块使用

新建测试类-TRbtTestData

新建包 com.test.invoice

再新建类 TRbtTestData

属性私有,行为公有

所以这里我们把属性设置为 private,通过 getset 来获取设置值

  1. package com.test.invoice.data;
  2. import com.alibaba.fastjson.annotation.JSONField;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.Data;
  5. import lombok.experimental.Accessors;
  6. @Data
  7. @Accessors(chain = true)
  8. public class TRbtTestData {
  9. @ApiModelProperty("名称")
  10. @JSONField(name = "name")
  11. private String name;
  12. @ApiModelProperty("版本号")
  13. @JSONField(name = "version")
  14. private String version;
  15. }

这个类引入了很多包,需要在 pom.xml 引入

父模块 pom.xml 引入包子模块 pom.xml 无法解析问题

问题描述

TRbtTestData 类需要引入一些包,我们再最外层 test-invoice-cloudpom.xml 中引入包

这个 pom.xml 中使用到了自定义变量,可以参考

pom.xml 中定义和使用变量

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <!--父级:Spring Boot-->
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <!--<version>2.0.1.RELEASE</version>-->
  10. <!--<version>2.0.3.RELEASE</version>--><!--解决循环引用对象问题mybatis https://github.com/heikehuan/springboot-multiple-dataSources/issues/2-->
  11. <version>2.0.9.RELEASE</version>
  12. </parent>
  13. <modelVersion>4.0.0</modelVersion>
  14. <groupId>com-test-invoice</groupId>
  15. <artifactId>test-invoice-cloud</artifactId>
  16. <packaging>pom</packaging>
  17. <version>1.0-SNAPSHOT</version>
  18. <name>test-invoice-cloud</name>
  19. <modules>
  20. <module>test-invoice-common</module>
  21. </modules>
  22. <properties>
  23. <fastjson.version>1.2.38</fastjson.version>
  24. <swagger.version>2.7.0</swagger.version>
  25. <lombok.version>1.18.6</lombok.version>
  26. </properties>
  27. <dependencies>
  28. <!--Spring Boot 执行器组件-->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-actuator</artifactId>
  32. </dependency>
  33. <!--Spring Cloud 基础-->
  34. <dependency>
  35. <groupId>org.springframework.cloud</groupId>
  36. <artifactId>spring-cloud-starter</artifactId>
  37. </dependency>
  38. <!--Spring Cloud 服务注册组件-->
  39. <dependency>
  40. <groupId>org.springframework.cloud</groupId>
  41. <!--此处的依赖是SpringBoot2.0以后专用的,如果您使用的SpringBoot版本低于2.0请使用spring-cloud-starter-eureka-server-->
  42. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  43. </dependency>
  44. <!--Spring Boot 测试组件-->
  45. <dependency>
  46. <groupId>org.springframework.boot</groupId>
  47. <artifactId>spring-boot-starter-test</artifactId>
  48. <scope>test</scope>
  49. </dependency>
  50. <!--Spring Boot Web组件-->
  51. <dependency>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-starter-web</artifactId>
  54. <!-- 从依赖信息里移除 Tomcat配置 -->
  55. <exclusions>
  56. <exclusion>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-starter-tomcat</artifactId>
  59. </exclusion>
  60. </exclusions>
  61. </dependency>
  62. <!-- spring aop start -->
  63. <dependency>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-starter-aop</artifactId>
  66. </dependency>
  67. <!-- spring aop end -->
  68. <!--fastJson start-->
  69. <!--Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库-->
  70. <dependency>
  71. <groupId>com.alibaba</groupId>
  72. <artifactId>fastjson</artifactId>
  73. <version>${fastjson.version}</version>
  74. </dependency>
  75. <!--fastJson end-->
  76. <!--swagger start-->
  77. <!--springfox是通过注解的形式自动生成API文档,利用它,可以很方便的书写restful API,swagger主要用于展示springfox生成的API文档-->
  78. <dependency>
  79. <groupId>io.springfox</groupId>
  80. <artifactId>springfox-swagger2</artifactId>
  81. <version>${swagger.version}</version>
  82. </dependency>
  83. <!--swagger end-->
  84. <!--lombok start-->
  85. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  86. <dependency>
  87. <groupId>org.projectlombok</groupId>
  88. <artifactId>lombok</artifactId>
  89. <version>${lombok.version}</version>
  90. </dependency>
  91. <!--lombok end-->
  92. </dependencies>
  93. </project>

test-invoice-commonpom.xml 中不引入,因为是父子模块,子模块就不用再引用了

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-common</artifactId>
  12. <name>test-invoice-common</name>
  13. </project>

构建,报下面的错误

  1. 程序包 xx 不存在

问题解决

原因是子模块没有引入对应包内容

打开右边的 Maven 选项卡,发现 test-invoice-common 没有 Dependencies 内容

test-invoice-commonpom.xml 中加入下面的内容

  1. <properties>
  2. <mybatisplus.version>3.1.0</mybatisplus.version>
  3. </properties>
  4. <dependencies>
  5. <!--MyBatis-Plus-->
  6. <dependency>
  7. <groupId>com.baomidou</groupId>
  8. <artifactId>mybatis-plus</artifactId>
  9. <version>${mybatisplus.version}</version>
  10. </dependency>
  11. </dependencies>

完整 pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-common</artifactId>
  12. <name>test-invoice-common</name>
  13. <properties>
  14. <mybatisplus.version>3.1.0</mybatisplus.version>
  15. </properties>
  16. <dependencies>
  17. <!--MyBatis-Plus-->
  18. <dependency>
  19. <groupId>com.baomidou</groupId>
  20. <artifactId>mybatis-plus</artifactId>
  21. <version>${mybatisplus.version}</version>
  22. </dependency>
  23. </dependencies>
  24. </project>

重新导入

导入成功后重新构建项目,成功

打开右边的 Maven 选项卡,Dependencies 内容出现

问题原因

去掉 在 test-invoice-commonpom.xml 中的内容

  1. <properties>
  2. <mybatisplus.version>3.1.0</mybatisplus.version>
  3. </properties>
  4. <dependencies>
  5. <!--MyBatis-Plus-->
  6. <dependency>
  7. <groupId>com.baomidou</groupId>
  8. <artifactId>mybatis-plus</artifactId>
  9. <version>${mybatisplus.version}</version>
  10. </dependency>
  11. </dependencies>

重新构建项目,也成功。

说明这个问题的原因是 IDE 不够智能引起的,有时候会加载不到对应的包引用,需要再重新构建才可以。

创建下图中的类和文件

类图

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-common</artifactId>
  12. <name>test-invoice-common</name>
  13. <properties>
  14. <mybatisplus.version>3.1.0</mybatisplus.version>
  15. </properties>
  16. <dependencies>
  17. <!--MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变-->
  18. <dependency>
  19. <groupId>com.baomidou</groupId>
  20. <artifactId>mybatis-plus</artifactId>
  21. <version>${mybatisplus.version}</version>
  22. </dependency>
  23. <!--Dozer是一个JavaBean映射工具库。它支持简单的属性映射,复杂类型映射,双向映射,隐式显式的映射,以及递归映射-->
  24. <dependency>
  25. <groupId>com.github.dozermapper</groupId>
  26. <artifactId>dozer-core</artifactId>
  27. <version>6.1.0</version>
  28. </dependency>
  29. <!--JUnit 是一个Java编程语言的单元测试框架-->
  30. <dependency>
  31. <groupId>junit</groupId>
  32. <artifactId>junit</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. <!--bouncy castle(轻量级密码术包)是一种用于 Java 平台的开放源码的轻量级密码术包;它支持大量的密码术算法,并提供JCE 1.2.1的实现-->
  36. <dependency>
  37. <groupId>org.bouncycastle</groupId>
  38. <artifactId>bcprov-jdk15on</artifactId>
  39. <version>1.55</version>
  40. </dependency>
  41. <!--密码加密框架-->
  42. <dependency>
  43. <groupId>com.madgag.spongycastle</groupId>
  44. <artifactId>core</artifactId>
  45. <version>1.54.0.0</version>
  46. </dependency>
  47. </dependencies>
  48. </project>

基础实体类-SuperEntity

  1. package com.test.invoice.model.base;
  2. import com.baomidou.mybatisplus.annotation.FieldFill;
  3. import com.baomidou.mybatisplus.annotation.IdType;
  4. import com.baomidou.mybatisplus.annotation.TableField;
  5. import com.baomidou.mybatisplus.annotation.TableId;
  6. import com.baomidou.mybatisplus.extension.activerecord.Model;
  7. import com.fasterxml.jackson.annotation.JsonFormat;
  8. import io.swagger.annotations.ApiModel;
  9. import io.swagger.annotations.ApiModelProperty;
  10. import lombok.Data;
  11. import lombok.EqualsAndHashCode;
  12. import lombok.experimental.Accessors;
  13. import java.io.Serializable;
  14. import java.util.Date;
  15. /**
  16. * 基础实体类
  17. *
  18. * @author:
  19. * @version:
  20. * @date: 2019-08-09 14:26
  21. */
  22. @EqualsAndHashCode(callSuper = true)
  23. @Data
  24. @Accessors(chain = true)
  25. public class SuperEntity<T extends Model> extends Model<T> {
  26. @TableId(type = IdType.UUID)
  27. @ApiModelProperty(value = "主键")
  28. private String id;
  29. @ApiModelProperty(value="创建时间",hidden = true)
  30. @TableField(value="create_time",fill = FieldFill.INSERT)
  31. @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
  32. private Date createTime;
  33. @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
  34. @ApiModelProperty(value = "修改时间", hidden = true)
  35. @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  36. private Date updateTime;
  37. @ApiModelProperty(value = "创建人", hidden = true)
  38. @TableField(value = "create_by", fill = FieldFill.INSERT)
  39. private String createBy;
  40. @ApiModelProperty(value = "修改人", hidden = true)
  41. @TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
  42. private String updateBy;
  43. @ApiModelProperty(value = "是否删除(0:未删除;1:已删除)", hidden = true)
  44. @TableField(value = "is_delete", fill = FieldFill.INSERT)
  45. private Integer isDelete;
  46. @ApiModelProperty(value = "系统时间戳", hidden = true)
  47. @TableField(value = "biz_time", fill = FieldFill.INSERT_UPDATE)
  48. @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  49. private Date bizTime;
  50. @Override
  51. protected Serializable pkVal() { return this.id; }
  52. }

t_rbt_test 表对应实体类-TRbtTestEntity

  1. package com.test.invoice.model;
  2. import com.baomidou.mybatisplus.annotation.TableName;
  3. import com.test.invoice.model.base.SuperEntity;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.Data;
  6. import lombok.EqualsAndHashCode;
  7. import lombok.ToString;
  8. import lombok.experimental.Accessors;
  9. /**
  10. * t_rbt_test 表对应实体类-TRbtTestEntity
  11. *
  12. * @author:
  13. * @version:
  14. * @date: 2019-08-09 14:25
  15. */
  16. @Data
  17. @EqualsAndHashCode(callSuper = true)
  18. @Accessors(chain = true)
  19. @ToString
  20. @TableName("t_rbt_test")
  21. public class TRbtTestEntity extends SuperEntity {
  22. @ApiModelProperty("名称")
  23. private String name;
  24. @ApiModelProperty("版本号")
  25. private String version;
  26. }

TRbtTestData 参数类

  1. package com.test.invoice.data;
  2. import com.alibaba.fastjson.annotation.JSONField;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.Data;
  5. import lombok.experimental.Accessors;
  6. /**
  7. * TRbtTestData 参数类
  8. *
  9. * @author:
  10. * @version:
  11. * @date: 2019-08-09 08:57
  12. */
  13. @Data
  14. @Accessors(chain = true) //@Accessors 注解用来配置lombok如何产生和显示getters和setters的方法。
  15. public class TRbtTestData {
  16. @ApiModelProperty("id")
  17. @JSONField(name = "id")
  18. private String id;
  19. @ApiModelProperty("名称")
  20. @JSONField(name = "name")
  21. private String name;
  22. @ApiModelProperty("版本号")
  23. @JSONField(name = "version")
  24. private String version;
  25. }

TRbtTestData 分页对象类

  1. package com.test.invoice.data;
  2. import com.alibaba.fastjson.annotation.JSONField;
  3. import com.test.invoice.model.base.SuperEntity;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.Data;
  6. import lombok.experimental.Accessors;
  7. /**
  8. * TRbtTestData 分页对象类
  9. *
  10. * @author:
  11. * @version:
  12. * @date: 2019-08-15 16:49
  13. */
  14. @Data
  15. @Accessors(chain = true) //@Accessors 注解用来配置lombok如何产生和显示getters和setters的方法。
  16. public class TRbtTestDataParam extends SuperEntity {
  17. @ApiModelProperty("当前页")
  18. @JSONField(name = "page")
  19. private Integer page;
  20. @ApiModelProperty("页面大小")
  21. @JSONField(name = "pageSize")
  22. private Integer pageSize;
  23. @ApiModelProperty("名称")
  24. @JSONField(name = "name")
  25. private String name;
  26. }

响应码枚举对象-ResponseCode

  1. package com.test.invoice.enums;
  2. /**
  3. * 响应码枚举对象。
  4. *
  5. * @author
  6. */
  7. public enum ResponseCode {
  8. //通用
  9. OK(2000, "Success"),
  10. INSERT_ERROR(-108, "新增失败"),
  11. DELETE_ERROR(-109, "数据删除失败,请刷新重试"),
  12. UPDATE_ERROR(-107, "更新失败,请刷新重试"),
  13. OPERATE_ERROR(5500, "操作失败"),
  14. PARAM_INVALID(1000, "缺失参数或无效"),
  15. THIRD_PARTY_EXCEPTION(3000, "第三方接口异常"),
  16. SYSTEM_EXCEPTION(5000, "系统异常"),
  17. SYSTEM_EXCEPTION_4(8004, "解析回调的xml出现异常"),
  18. SYSTEM_EXCEPTION_8(8008, "JSON转换错误"),
  19. SYSTEM_EXCEPTION_9(8009, "HTTP请求异常"),
  20. SYSTEM_EXCEPTION_10(8010, "用户权限不够"),
  21. SYSTEM_EXCEPTION_11(8011, "获取用户信息失败"),
  22. SYSTEM_EXCEPTION_13(8013, "查询用户出现异常"),
  23. SYSTEM_EXCEPTION_14(8014, "获取用户信息失败,请核实用户id"),
  24. SYSTEM_EXCEPTION_16(8888, "获取用户信息失败,请核实用户id"),
  25. SYSTEM_EXCEPTION_18(8888, "用户权限不够"),
  26. SYSTEM_EXCEPTION_20(8888, "获取用户信息失败"),
  27. SYSTEM_EXCEPTION_21(8888, "调用失败"),
  28. ACCESS_TOKEN_EXCEPTION(9000, "获取token失败"),
  29. AUTH_INVALID(4000, "身份验证失败"),
  30. TOKEN_MISSING(4001, "token缺失"),
  31. TOKEN_INVALID(4002, "token Fail"),
  32. ;
  33. private final int value;
  34. private final String description;
  35. ResponseCode(int value, String description) {
  36. this.value = value;
  37. this.description = description;
  38. }
  39. public int value() {
  40. return this.value;
  41. }
  42. public String getDescription() {
  43. return this.description;
  44. }
  45. public static ResponseCode valueOf(int code) {
  46. for (ResponseCode responseCode : values()) {
  47. if (responseCode.value == code) {
  48. return responseCode;
  49. }
  50. }
  51. throw new IllegalArgumentException("No matching constant for [" + code + "]");
  52. }
  53. @Override
  54. public String toString() {
  55. return Integer.toString(this.value);
  56. }
  57. }

服务异常类-ServiceException

  1. package com.test.invoice.excepiton;
  2. import com.test.invoice.enums.ResponseCode;
  3. /**
  4. * 服务异常类
  5. *
  6. * @author:
  7. * @version:
  8. * @date: 2019-08-09 10:28
  9. */
  10. public class ServiceException extends RuntimeException {
  11. private int code;
  12. public ServiceException(ResponseCode responseCode,Throwable cause){
  13. super(responseCode.getDescription(),cause);
  14. this.code = responseCode.value();
  15. }
  16. public ServiceException(ResponseCode responseCode){
  17. super(responseCode.getDescription());
  18. this.code = responseCode.value();
  19. }
  20. public int getCode() { return code; }
  21. public void setCode(int code) { this.code = code; }
  22. }

响应实体-ResponseVO

VO:value object 值对象/ view object 表现层对象
1.主要对应页面显示(web 页面 / swt 、swing 界面)的数据对象
2.可以和表对应,也可以不对应,根据业务需要。

  1. package com.test.invoice.vo;
  2. import com.fasterxml.jackson.annotation.JsonInclude;
  3. import com.test.invoice.enums.ResponseCode;
  4. import com.test.invoice.excepiton.ServiceException;
  5. import io.swagger.annotations.ApiModel;
  6. import io.swagger.annotations.ApiModelProperty;
  7. import lombok.AllArgsConstructor;
  8. import lombok.Data;
  9. import lombok.NoArgsConstructor;
  10. import lombok.experimental.Accessors;
  11. import java.io.Serializable;
  12. /**
  13. * 响应实体
  14. *
  15. * @author:
  16. * @version:
  17. * @date: 2019-08-09 10:40
  18. */
  19. @Data
  20. @AllArgsConstructor
  21. @NoArgsConstructor
  22. @JsonInclude(JsonInclude.Include.NON_NULL)
  23. @ApiModel("响应实体")
  24. @Accessors(chain = true)
  25. public class ResponseVO<T> implements Serializable {
  26. private static final long serialVersionUID = 1L;
  27. @ApiModelProperty("编码 200:成功,其他异常")
  28. private Integer code;
  29. @ApiModelProperty("消息")
  30. private String msg;
  31. @ApiModelProperty("数据结果集")
  32. private T data;
  33. @ApiModelProperty("服务器时间戳")
  34. private Long timestamp;
  35. public ResponseVO(ResponseCode responseCode){
  36. this.code = responseCode.value();
  37. this.msg = responseCode.getDescription();
  38. this.timestamp = System.currentTimeMillis();
  39. }
  40. public ResponseVO(ResponseCode responseCode,T data){
  41. this.code = responseCode.value();
  42. this.msg = responseCode.getDescription();
  43. this.timestamp = System.currentTimeMillis();
  44. this.data = data;
  45. }
  46. public ResponseVO(ServiceException e){
  47. this.code = e.getCode();
  48. this.msg = e.getMessage();
  49. }
  50. public ResponseVO(int code, String msg){
  51. this.code = code;
  52. this.msg = msg;
  53. this.timestamp = System.currentTimeMillis();
  54. }
  55. }

创建子模块-test-invoice-contract

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-contract

模块名称 test-invoice-contract

创建包重复问题

新建包 com.test.invoice.service

再建一个子包 db

再建一个和 db 包同级的包 test

这时候发现并不同级

解决

新建好包 com.test.invoice.service 之后创建类 Test,再创建包

新建类-TRbtTestConsumer

  1. package com.test.invoice.service.consumer;
  2. import org.springframework.cloud.openfeign.FeignClient;
  3. import org.springframework.web.bind.annotation.*;
  4. import com.test.invoice.data.TRbtTestData;
  5. /**
  6. * TRbtTestConsumer
  7. *
  8. * @author:
  9. * @version:
  10. * @date: 2019-08-08 14:45
  11. */
  12. @FeignClient(value = "service-producer")
  13. public class TRbtTestConsumer {
  14. public void Test()
  15. {
  16. TRbtTestData data = new TRbtTestData();
  17. }
  18. }

pom.xml 引用

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-contract</artifactId>
  12. <name>test-invoice-contract</name>
  13. <dependencies>
  14. <dependency>
  15. <groupId>com.test.invoice</groupId>
  16. <artifactId>test-invoice-common</artifactId>
  17. <version>1.0-SNAPSHOT</version>
  18. </dependency>
  19. <!--feign start-->
  20. <dependency>
  21. <groupId>org.springframework.cloud</groupId>
  22. <!--spring boot 2.0.3版本解决方案:spring-cloud-starter-feign-->
  23. <artifactId>spring-cloud-starter-openfeign</artifactId>
  24. </dependency>
  25. <!--feign end-->
  26. </dependencies>
  27. <build>
  28. </build>
  29. <properties>
  30. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  31. </properties>
  32. </project>

报错-Dependency ‘xxx’ not found 及解决

  1. Dependency 'com.test.invoice:test-invoice-common:1.0-SNAPSHOT' not found

参考文档

maven多module项目的引用问题

我对比三个 pom.xml 文件

test-invoice-cloud
pom.xml

  1. <modelVersion>4.0.0</modelVersion>
  2. <groupId>com-test-invoice</groupId>
  3. <artifactId>test-invoice-cloud</artifactId>
  4. <version>1.0-SNAPSHOT</version>
  5. <name>test-invoice-cloud</name>
  6. <packaging>pom</packaging>

test-invoice-common
pom.xml

  1. <parent>
  2. <artifactId>test-invoice-cloud</artifactId>
  3. <groupId>com-test-invoice</groupId>
  4. <version>1.0-SNAPSHOT</version>
  5. </parent>
  6. <modelVersion>4.0.0</modelVersion>
  7. <artifactId>test-invoice-common</artifactId>
  8. <name>test-invoice-common</name>

test-invoice-contract
pom.xml

  1. <parent>
  2. <artifactId>test-invoice-cloud</artifactId>
  3. <groupId>com-test-invoice</groupId>
  4. <version>1.0-SNAPSHOT</version>
  5. </parent>
  6. <modelVersion>4.0.0</modelVersion>
  7. <artifactId>test-invoice-contract</artifactId>
  8. <name>test-invoice-contract</name>
  9. <dependency>
  10. <groupId>com.test.invoice</groupId>
  11. <artifactId>test-invoice-common</artifactId>
  12. <version>1.0-SNAPSHOT</version>
  13. </dependency>

问题原因

  1. <dependency>
  2. <groupId>com.test.invoice</groupId>

问题解决,修改为

  1. <dependency>
  2. <groupId>com-test-invoice</groupId>

创建下图中的类和文件

模块简介

主要用于提供接口,还有 Feign-api 接口

类图

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-contract</artifactId>
  12. <name>test-invoice-contract</name>
  13. <dependencies>
  14. <dependency>
  15. <groupId>com-test-invoice</groupId>
  16. <artifactId>test-invoice-common</artifactId>
  17. <version>1.0-SNAPSHOT</version>
  18. </dependency>
  19. <!--feign start-->
  20. <dependency>
  21. <groupId>org.springframework.cloud</groupId>
  22. <!--spring boot 2.0.3版本解决方案:spring-cloud-starter-feign-->
  23. <artifactId>spring-cloud-starter-openfeign</artifactId>
  24. </dependency>
  25. <!--feign end-->
  26. </dependencies>
  27. <build>
  28. </build>
  29. <properties>
  30. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  31. </properties>
  32. </project>

接口定义-ITRbtTestService

  1. package com.test.invoice.service.producer;
  2. import com.test.invoice.data.TRbtTestData;
  3. import com.test.invoice.data.TRbtTestDataParam;
  4. import com.test.invoice.vo.ResponseVO;
  5. import org.springframework.web.bind.annotation.RequestBody;
  6. import org.springframework.web.bind.annotation.*;
  7. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  8. /**
  9. * 接口定义-ITRbtTestService
  10. */
  11. public interface ITRbtTestService {
  12. ResponseVO<String> Add(@RequestBody TRbtTestData data);
  13. ResponseVO<Boolean> Update(@RequestBody TRbtTestData data);
  14. ResponseVO<Boolean> Del(@RequestParam(value="name",required = true) String name,@RequestParam(value="version",required = true) String version);
  15. ResponseVO<TRbtTestData> Get(@RequestBody TRbtTestData data);
  16. ResponseVO<Page<TRbtTestData>> Query(@RequestBody TRbtTestDataParam param);
  17. }

Feign-api 接口定义——TRbtTestConsumer

  1. package com.test.invoice.service.consumer;
  2. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  3. import com.test.invoice.vo.ResponseVO;
  4. import org.springframework.cloud.openfeign.FeignClient;
  5. import org.springframework.web.bind.annotation.*;
  6. import com.test.invoice.data.TRbtTestData;
  7. import com.test.invoice.data.TRbtTestDataParam;
  8. /**
  9. * Feign-api 接口定义——TRbtTestConsumer
  10. *
  11. * @author:
  12. * @version:
  13. * @date: 2019-08-08 14:45
  14. */
  15. @FeignClient(value = "service-producer")
  16. public interface TRbtTestConsumer {
  17. @PostMapping("/Test/Add")
  18. ResponseVO<String> Add(@RequestBody TRbtTestData data);
  19. @PostMapping("Test/Update")
  20. ResponseVO<Boolean> Update(@RequestBody TRbtTestData data);
  21. @RequestMapping(value="Test/Del",method=RequestMethod.GET)
  22. ResponseVO<Boolean> Del(@RequestParam(value="name",required = true) String name,@RequestParam(value="version",required = true) String version);
  23. @PostMapping("/Test/Get")
  24. ResponseVO<TRbtTestData> Get(@RequestBody TRbtTestData data);
  25. @PostMapping("/Test/Query")
  26. ResponseVO<Page<TRbtTestData>> Query(@RequestBody TRbtTestDataParam param);
  27. }

创建子模块-test-invoice-service

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-service

模块名称 test-invoice-service

创建下图中的类和文件

模块简介

作为一个 Eureka Client 模块

实现 test-invoice-contract 项目中定义的接口

类图

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>test-invoice-cloud</artifactId>
  7. <groupId>com-test-invoice</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>test-invoice-service</artifactId>
  12. <name>test-invoice-service</name>
  13. <dependencies>
  14. <dependency>
  15. <groupId>com-test-invoice</groupId>
  16. <artifactId>test-invoice-contract</artifactId>
  17. <version>1.0-SNAPSHOT</version>
  18. </dependency>
  19. <!--Apache PDFbox 是一个开源的、基于 Java 的、支持 PDF 文档生成的工具库-->
  20. <dependency>
  21. <groupId>org.apache.pdfbox</groupId>
  22. <artifactId>fontbox</artifactId>
  23. <version>2.0.1</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.apache.pdfbox</groupId>
  27. <artifactId>pdfbox</artifactId>
  28. <version>2.0.4</version>
  29. </dependency>
  30. <!--iText是一个能够快速产生PDF文件的java类库-->
  31. <dependency>
  32. <groupId>com.lowagie</groupId>
  33. <artifactId>itext</artifactId>
  34. <version>2.1.7</version>
  35. </dependency>
  36. <!--mysql start-->
  37. <dependency>
  38. <groupId>mysql</groupId>
  39. <artifactId>mysql-connector-java</artifactId>
  40. </dependency>
  41. <!--mysql end-->
  42. <!--保存到数据库需要如下依赖-->
  43. <!--<dependency>
  44. <groupId>mysql</groupId>
  45. <artifactId>mysql-connector-java</artifactId>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-jdbc</artifactId>
  50. </dependency>-->
  51. <!--db start-->
  52. <!--号称性能最好的JDBC连接池-->
  53. <dependency>
  54. <groupId>com.zaxxer</groupId>
  55. <artifactId>HikariCP</artifactId>
  56. <version>${HikariCP.version}</version>
  57. </dependency>
  58. <!--db end-->
  59. <dependency>
  60. <groupId>com.baomidou</groupId>
  61. <artifactId>mybatis-plus-boot-starter</artifactId>
  62. <version>${mybatis-plus-spring-boot-starter.version}</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>org.apache.commons</groupId>
  66. <artifactId>commons-pool2</artifactId>
  67. </dependency>
  68. <!--redis start-->
  69. <dependency>
  70. <groupId>org.springframework.boot</groupId>
  71. <artifactId>spring-boot-starter-data-redis</artifactId>
  72. </dependency>
  73. <!--redis end-->
  74. <!--分布式链路追踪三个依赖-->
  75. <!--<dependency>
  76. <groupId>org.springframework.cloud</groupId>
  77. <artifactId>spring-cloud-starter-sleuth</artifactId>
  78. </dependency>
  79. <dependency>
  80. <groupId>org.springframework.boot</groupId>
  81. <artifactId>spring-boot-starter-webflux</artifactId>
  82. </dependency>-->
  83. <dependency>
  84. <groupId>org.springframework.cloud</groupId>
  85. <artifactId>spring-cloud-starter-zipkin</artifactId>
  86. </dependency>
  87. <!--activiti start-->
  88. <dependency>
  89. <groupId>org.activiti</groupId>
  90. <artifactId>activiti-spring-boot-starter-basic</artifactId>
  91. <version>6.0.0</version>
  92. </dependency>
  93. <!--activiti end-->
  94. </dependencies>
  95. <build>
  96. <finalName>${project.artifactId}</finalName>
  97. <plugins>
  98. <plugin>
  99. <groupId>org.springframework.boot</groupId>
  100. <artifactId>spring-boot-maven-plugin</artifactId>
  101. <configuration>
  102. <fork>true</fork>
  103. </configuration>
  104. <!--如果要访问info接口想获取maven中的属性内容请记得添加如下内容-->
  105. <executions>
  106. <execution>
  107. <goals>
  108. <goal>build-info</goal>
  109. </goals>
  110. </execution>
  111. </executions>
  112. </plugin>
  113. </plugins>
  114. <resources>
  115. <resource>
  116. <directory>src/main/resources</directory>
  117. <includes>
  118. <include>**/*</include>
  119. </includes>
  120. </resource>
  121. </resources>
  122. </build>
  123. </project>

Resources

自定义分页映射xml-TRbtTestMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.test.invoice.mapper.TRbtTestRepository">
  4. <select id="selectPageVO" resultType="com.test.invoice.data.TRbtTestData"
  5. parameterType="com.test.invoice.data.TRbtTestDataParam">
  6. select id,name,version from t_rbt_test where name = #{param.name}
  7. </select>
  8. </mapper>

application.yml

  1. server:
  2. port: 18800
  3. spring:
  4. profiles:
  5. active: dev # 指定配置文件
  6. http:
  7. encoding:
  8. force: true # 默认编码,即 utf8
  9. activiti:
  10. check-process-definitions: false # 校验流程文件,默认校验resources下的processes文件夹里的流程文件
  11. # 服务名称,即serviceId
  12. application:
  13. name: service-producer
  14. sleuth:
  15. web:
  16. client:
  17. enabled: true # 启用为分布式web client 客户端
  18. sampler:
  19. probability: 1.0 # 将采样比例设置为 1.0,也就是全部都需要。默认是 0.1

application-dev.yml

  1. spring:
  2. datasource:
  3. type: com.zaxxer.hikari.HikariDataSource #数据源类型
  4. url: jdbc:mysql://localhost:3306/luoma_test?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false #数据库url
  5. username: root #数据库用户名
  6. password: luoma_LUOMA #数据库密码
  7. driver-class-name: com.mysql.jdbc.Driver #数据库驱动
  8. hikari:
  9. pool-name: pool-vscloud
  10. connectionTestQuery: SELECT 1
  11. maximum-pool-size: 50
  12. minimum-idle: 10
  13. #mybatis
  14. mybatis-plus:
  15. mapper-locations: classpath:/mapper/*Mapper.xml #mybatis-plus mapper xml 文件地址
  16. #实体扫描,多个package用逗号或者分号分隔
  17. typeAliasesPackage:
  18. typeEnumsPackage:
  19. global-config:
  20. id-type: 4
  21. #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
  22. field-strategy: 2
  23. #驼峰下划线转换
  24. db-column-underline: true
  25. #刷新mapper 调试神器
  26. refresh-mapper: true
  27. #数据库大写下划线转换
  28. #capital-mode: true
  29. #序列接口实现类配置
  30. #key-generator:
  31. #逻辑删除配置
  32. logic-delete-value: 0
  33. logic-not-delete-value: 1
  34. configuration:
  35. map-underscore-to-camel-case: true
  36. cache-enabled: false
  37. # 服务注册与发现相关配置
  38. eureka:
  39. #自定义实例编号
  40. instance:
  41. instance-id: ${spring.application.name}:${server.port}
  42. # 优先使用IP地址方式进行注册服务
  43. prefer-ip-address: true
  44. # 配置使用指定IP
  45. client:
  46. # 服务注册地址
  47. serviceUrl:
  48. defaultZone: http://127.0.0.1:8772/eureka/

application-test.yml

  1. #spring
  2. spring:
  3. datasource:
  4. type: com.zaxxer.hikari.HikariDataSource
  5. url: jdbc:mysql://localhost:3306/luoma_test?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false
  6. username: root
  7. password: luoma_ai_LEIMU
  8. driver-class-name: com.mysql.jdbc.Driver
  9. hikari:
  10. pool-name: pool-vscloud
  11. connectionTestQuery: SELECT 1
  12. maximum-pool-size: 50
  13. minimum-idle: 10
  14. #mybatis
  15. mybatis-plus:
  16. mapper-locations: classpath:/mapper/*Mapper.xml
  17. #实体扫描,多个package用逗号或者分号分隔
  18. typeAliasesPackage:
  19. typeEnumsPackage:
  20. global-config:
  21. #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
  22. id-type: 0
  23. #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
  24. field-strategy: 2
  25. #驼峰下划线转换
  26. db-column-underline: true
  27. #刷新mapper 调试神器
  28. refresh-mapper: true
  29. #数据库大写下划线转换
  30. #capital-mode: true
  31. #序列接口实现类配置
  32. #key-generator:
  33. #逻辑删除配置
  34. logic-delete-value: 0
  35. logic-not-delete-value: 1
  36. # #自定义填充策略接口实现
  37. # meta-object-handler:
  38. configuration:
  39. map-underscore-to-camel-case: true
  40. cache-enabled: false

bootstrap.properties

  1. #由于 logback-spring.xml的加载在 application.properties之前,所以之前的配置 logback-spring.xml无法获取到 spring.application.name属性,因此这里将该属性移动到最先加载的 bootstrap.properties配置文件中。
  2. #https://cloud.tencent.com/developer/article/1067431
  3. spring.application.name=service-producer

MybatisPlus 配置类-MybatisPlusConfig

  1. package com.test.invoice.config;
  2. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  3. import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
  4. import org.mybatis.spring.mapper.MapperScannerConfigurer;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.Profile;
  8. /**
  9. * 从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
  10. */
  11. @Configuration
  12. public class MybatisPlusConfig {
  13. /**
  14. * mybatis-plus SQL执行效率插件【生产环境可以关闭】
  15. */
  16. @Bean
  17. //@Profile({"dev", "test"})// 设置 dev test 环境开启
  18. @Profile({"dev"})// 设置 dev test 环境开启
  19. public PerformanceInterceptor performanceInterceptor() {
  20. return new PerformanceInterceptor();
  21. }
  22. /**
  23. * mybatis-plus分页插件<br>
  24. * 文档:http://mp.baomidou.com<br>
  25. */
  26. @Bean
  27. public PaginationInterceptor paginationInterceptor() {
  28. PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
  29. // paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
  30. return paginationInterceptor;
  31. }
  32. /**
  33. * 相当于顶部的:
  34. * {@code @MapperScan("com.baomidou.springboot.mapper*")}
  35. * 这里可以扩展,比如使用配置文件来配置扫描Mapper的路径
  36. */
  37. @Bean
  38. public MapperScannerConfigurer mapperScannerConfigurer() {
  39. MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
  40. scannerConfigurer.setBasePackage("com.test.invoice.mapper*");
  41. return scannerConfigurer;
  42. }
  43. }

MybatisPlus 配置类-MyMetaObjectHandler

  1. package com.test.invoice.config;
  2. import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.ibatis.reflection.MetaObject;
  5. import org.springframework.stereotype.Component;
  6. import java.util.Date;
  7. /**
  8. * mybatis公共字段自动填充
  9. *
  10. */
  11. @Slf4j
  12. @Component
  13. public class MyMetaObjectHandler implements MetaObjectHandler {
  14. @Override
  15. public void insertFill(MetaObject metaObject) {
  16. String user="luoma";
  17. try {
  18. log.info("【填充数据 --开始】");
  19. this.setFieldValByName("createTime", new Date(), metaObject);
  20. this.setFieldValByName("updateTime", new Date(), metaObject);
  21. this.setFieldValByName("bizTime", new Date(), metaObject);
  22. this.setFieldValByName("isDelete", 0, metaObject);
  23. this.setFieldValByName("createBy", user, metaObject);
  24. this.setFieldValByName("updateBy", user, metaObject);
  25. log.info("【填充数据 --完毕】");
  26. } catch (Exception e) {
  27. log.info("填充错误" + e.getMessage());
  28. }
  29. }
  30. /**
  31. * description 更新自动填充
  32. */
  33. @Override
  34. public void updateFill(MetaObject metaObject) {
  35. String user="luoma";
  36. this.setFieldValByName("updateTime", new Date(), metaObject);
  37. this.setFieldValByName("bizTime", new Date(), metaObject);
  38. this.setFieldValByName("updateBy", user, metaObject);
  39. log.info("【填充数据 --完毕】");
  40. }
  41. }

自定义接口-TRbtTestRepository

  1. package com.test.invoice.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.test.invoice.data.TRbtTestData;
  6. import com.test.invoice.data.TRbtTestDataParam;
  7. import com.test.invoice.model.TRbtTestEntity;
  8. import org.springframework.stereotype.Repository;
  9. @Repository
  10. public interface TRbtTestRepository extends BaseMapper<TRbtTestEntity> {
  11. IPage<TRbtTestData> selectPageVO(Page<TRbtTestData> page, TRbtTestDataParam param);
  12. }

接口实现-TRbtTestServiceImpl

  1. package com.test.invoice.service.impl;
  2. import com.test.invoice.data.TRbtTestDataParam;
  3. import com.test.invoice.enums.ResponseCode;
  4. import com.test.invoice.vo.ResponseVO;
  5. import com.test.invoice.data.TRbtTestData;
  6. import com.test.invoice.mapper.TRbtTestRepository;
  7. import com.test.invoice.model.TRbtTestEntity;
  8. import com.test.invoice.service.producer.ITRbtTestService;
  9. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  10. import com.baomidou.mybatisplus.core.metadata.IPage;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  13. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.springframework.stereotype.Service;
  16. import org.springframework.web.bind.annotation.RequestBody;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import java.util.List;
  19. /**
  20. * TRbtTestServiceImpl
  21. *
  22. * @author:
  23. * @version:
  24. * @date: 2019-08-12 10:23
  25. */
  26. @Slf4j
  27. @Service
  28. public class TRbtTestServiceImpl extends ServiceImpl<TRbtTestRepository, TRbtTestEntity> implements ITRbtTestService {
  29. @Override
  30. public ResponseVO<String> Add(@RequestBody TRbtTestData data){
  31. TRbtTestEntity entity = new TRbtTestEntity();
  32. entity.setName(data.getName()).setVersion(data.getVersion());
  33. if(baseMapper.insert(entity) > 0){
  34. return new ResponseVO<>(ResponseCode.OK);
  35. }
  36. return new ResponseVO<>(ResponseCode.OPERATE_ERROR,"ERROR");
  37. }
  38. @Override
  39. public ResponseVO<Boolean> Update(@RequestBody TRbtTestData data){
  40. UpdateWrapper<TRbtTestEntity> wrapper = new UpdateWrapper<>();
  41. wrapper.set("name",data.getName()).set("version",data.getVersion());
  42. wrapper.eq("id",data.getId());
  43. return new ResponseVO<>(ResponseCode.OK,update(wrapper));
  44. }
  45. @Override
  46. public ResponseVO<Boolean> Del(@RequestParam(value="name",required = true) String name, @RequestParam(value="version",required = true) String version){
  47. UpdateWrapper<TRbtTestEntity> wrapper = new UpdateWrapper<>();
  48. wrapper.eq("name",name);
  49. wrapper.eq("version",version);
  50. return new ResponseVO<>(ResponseCode.OK, baseMapper.delete(wrapper) > 0);
  51. }
  52. @Override
  53. public ResponseVO<TRbtTestData> Get(@RequestBody TRbtTestData data){
  54. List<TRbtTestEntity> list = baseMapper.selectList(Wrappers.<TRbtTestEntity>lambdaQuery().eq(TRbtTestEntity::getName, data.getName()));
  55. if(!list.isEmpty()){
  56. TRbtTestEntity entity = list.get(0);
  57. data.setName(entity.getName());
  58. data.setVersion(entity.getVersion());
  59. return new ResponseVO<>(ResponseCode.OK, data);
  60. }else{
  61. return new ResponseVO<>(ResponseCode.PARAM_INVALID, data);
  62. }
  63. }
  64. @Override
  65. public ResponseVO<Page<TRbtTestData>> Query(@RequestBody TRbtTestDataParam param){
  66. Page<TRbtTestData> page = new Page<>();
  67. page.setCurrent(param.getPage());
  68. page.setSize(param.getPageSize());
  69. //return new ResponseVO<>(ResponseCode.OK, baseMapper.selectPageVO(page, param));
  70. IPage<TRbtTestData> ipageData = baseMapper.selectPageVO(page, param);
  71. //IPage<TRbtTestData> 转换为 Page<TRbtTestData>
  72. Page<TRbtTestData> pageData = new Page<>();
  73. pageData.setRecords(ipageData.getRecords());
  74. pageData.setCurrent(ipageData.getCurrent());
  75. pageData.setSize(ipageData.getSize());
  76. pageData.setTotal(ipageData.getTotal());
  77. return new ResponseVO<>(ResponseCode.OK, pageData);
  78. }
  79. }

生产者:业务微服务-测试框架系统控制类-TRbtTestController

  1. package com.test.invoice.contorller;
  2. import com.test.invoice.data.TRbtTestData;
  3. import com.test.invoice.data.TRbtTestDataParam;
  4. import com.test.invoice.service.producer.ITRbtTestService;
  5. import com.test.invoice.vo.ResponseVO;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import io.swagger.annotations.Api;
  11. import io.swagger.annotations.ApiOperation;
  12. import org.springframework.web.bind.annotation.*;
  13. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  14. import javax.annotation.Resource;
  15. /**
  16. *
  17. * 生产者:业务微服务-测试框架系统控制类
  18. *
  19. * @author:
  20. * @version:
  21. * @date: 2019-08-12 09:53
  22. */
  23. @RestController
  24. @Api(description = "测试框架系统控制类")
  25. public class TRbtTestController {
  26. @Resource
  27. private ITRbtTestService testService;
  28. @PostMapping("/Test/Add")
  29. @ApiOperation(value="系统框架测试-新增数据",httpMethod = "POST",response = ResponseVO.class,notes = "系统框架测试-新增数据")
  30. public ResponseVO Add(@RequestBody TRbtTestData data){
  31. return testService.Add(data);
  32. }
  33. @PostMapping("Test/Update")
  34. @ApiOperation(value="系统框架测试-修改数据",httpMethod = "POST",response = ResponseVO.class,notes = "系统框架测试-修改数据")
  35. public ResponseVO<Boolean> Update(@RequestBody TRbtTestData data){
  36. return testService.Update(data);
  37. }
  38. @RequestMapping(value="Test/Del",method = RequestMethod.GET)
  39. @ApiOperation(value="系统框架测试-删除数据",httpMethod = "GET",response = ResponseVO.class,notes = "系统框架测试-删除数据")
  40. public ResponseVO<Boolean> Del(@RequestParam(value="name",required = true) String name,@RequestParam(value="version",required = true) String version)
  41. {
  42. return testService.Del(name,version);
  43. }
  44. @PostMapping("/Test/Get")
  45. @ApiOperation(value="系统框架测试-获取单个数据",httpMethod = "POST",response = ResponseVO.class,notes = "系统框架测试-获取单个数据")
  46. public ResponseVO<TRbtTestData> Get(@RequestBody TRbtTestData data){
  47. return testService.Get(data);
  48. }
  49. @PostMapping("/Test/Query")
  50. @ApiOperation(value="系统框架测试-查询分页数据",httpMethod = "POST",response = ResponseVO.class,notes = "系统框架测试-查询分页数据")
  51. public ResponseVO<Page<TRbtTestData>> Query(@RequestBody TRbtTestDataParam param){
  52. return testService.Query(param);
  53. }
  54. }

入口类-ServerApplication

  1. package com.test.invoice;
  2. import org.activiti.spring.boot.SecurityAutoConfiguration;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /**
  8. * 启动类
  9. *
  10. * @author:
  11. * @version:
  12. * @date: 2019-08-12 09:53
  13. */
  14. @SpringBootApplication(exclude = SecurityAutoConfiguration.class) //禁用 security 验证
  15. @RestController
  16. @EnableEurekaClient //Eureka Client
  17. public class ServerApplication {
  18. public static void main(String[] args){
  19. SpringApplication.run(ServerApplication.class,args);
  20. }
  21. }

测试结果

启动项目 test-invoice-eureka
启动项目 test-invoice-service

启动多个项目参考

启动多个项目

首先访问 http://localhost:8772/ ,看 Instances currently registered with Eureka 是否能看到 test-invoice-service 项目

接着使用 Postman 调用 test-invoice-service 接口 Add

结果

创建子模块-test-invoice-web

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-web

模块名称 test-invoice-web

创建下图中的类和文件

模块简介

作为一个 Eureka 客户端,提供调用接口

类图

pom.xml

  1. server:
  2. port: 8080
  3. servlet:
  4. context-path: /enta/api
  5. spring:
  6. application:
  7. # 服务名,即serviceId
  8. name: service-feign-web
  9. sleuth:
  10. web:
  11. client:
  12. enabled: true # 启用为分布式web client 客户端
  13. sampler:
  14. probability: 1.0 # 将采样比例设置为 1.0,也就是全部都需要。默认是 0.1
  15. # 服务注册与发现相关配置
  16. eureka:
  17. #自定义实例编号
  18. instance:
  19. instance-id: ${spring.application.name}:${server.port}
  20. # 优先使用IP地址方式进行注册服务
  21. prefer-ip-address: true
  22. # 配置使用指定IP
  23. # ip-address: 127.0.0.1
  24. client:
  25. # 服务注册地址
  26. serviceUrl:
  27. # defaultZone: http://127.0.0.1:8772/eureka/
  28. defaultZone: http://127.0.0.1:8772/eureka/
  29. #配置actuator的相关配置
  30. # 描述信息
  31. info:
  32. blog-url: http://luoma.pro
  33. author: luoma
  34. # 加载所有的端点/默认只加载了 info / health
  35. management:
  36. endpoints:
  37. web:
  38. exposure:
  39. include: "*"
  40. endpoint:
  41. health:
  42. show-details: always
  43. shutdown:
  44. enabled: false # 可以关闭制定的端点

bootstrap.properties

  1. #由于 logback-spring.xml的加载在 application.properties之前,所以之前的配置 logback-spring.xml无法获取到 spring.application.name属性,因此这里将该属性移动到最先加载的 bootstrap.properties配置文件中。
  2. #https://cloud.tencent.com/developer/article/1067431
  3. spring.application.name=service-feign-web

消费者,通过 Feign-api 调用-TRbtTestController

  1. package com.test.invoice.controller;
  2. import com.test.invoice.data.TRbtTestData;
  3. import com.test.invoice.data.TRbtTestDataParam;
  4. import com.test.invoice.service.consumer.TRbtTestConsumer;
  5. import com.test.invoice.vo.ResponseVO;
  6. import io.swagger.annotations.Api;
  7. import io.swagger.annotations.ApiOperation;
  8. import org.springframework.web.bind.annotation.*;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. /**
  11. * 消费者,通过 Feign-api 调用
  12. *
  13. * @author:
  14. * @version:
  15. * @date: 2019-08-12 14:49
  16. */
  17. @RestController
  18. @Api(description = "测试框架系统控制类")
  19. @RequestMapping("/Inv/Api")
  20. public class TRbtTestController {
  21. //@Resource
  22. @Autowired
  23. private TRbtTestConsumer testConsumer;
  24. @PostMapping("Test/Add")
  25. @ApiOperation(value = "系统框架测试-新增数据", httpMethod = "POST", response = ResponseVO.class, notes = "系统框架测试-新增数据")
  26. public ResponseVO Add(@RequestBody TRbtTestData data){
  27. return testConsumer.Add(data);
  28. }
  29. @PostMapping("Test/Update")
  30. @ApiOperation(value = "系统框架测试-修改数据", httpMethod = "POST", response = ResponseVO.class, notes = "系统框架测试-修改数据")
  31. public ResponseVO Update(@RequestBody TRbtTestData data){
  32. return testConsumer.Update(data);
  33. }
  34. @RequestMapping(value="Test/Del",method=RequestMethod.GET)
  35. @ApiOperation(value = "系统框架测试-删除数据", httpMethod = "POST", response = ResponseVO.class, notes = "系统框架测试-删除数据")
  36. public ResponseVO Del(@RequestParam(value="name",required = true) String name,@RequestParam(value="version",required = true) String version){
  37. return testConsumer.Del(name,version);
  38. }
  39. @PostMapping("/Test/Get")
  40. @ApiOperation(value = "系统框架测试-获取单个数据", httpMethod = "POST", response = ResponseVO.class, notes = "系统框架测试-获取单个数据")
  41. public ResponseVO Get(@RequestBody TRbtTestData data){
  42. return testConsumer.Get(data);
  43. }
  44. @PostMapping("/Test/Query")
  45. @ApiOperation(value = "系统框架测试-获取分页数据", httpMethod = "POST", response = ResponseVO.class, notes = "系统框架测试-获取分页数据")
  46. public ResponseVO Query(@RequestBody TRbtTestDataParam param){
  47. return testConsumer.Query(param);
  48. }
  49. }

启动类-WebApplication

  1. package com.test.invoice;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. import org.springframework.cloud.openfeign.EnableFeignClients;
  6. /**
  7. * 启动类
  8. *
  9. * @author:
  10. * @version:
  11. * @date: 2019-08-12 14:43
  12. */
  13. //禁用 security 验证
  14. @SpringBootApplication(exclude = org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class)
  15. @EnableFeignClients //使用feign客户端,https://blog.csdn.net/andy_zhang2007/article/details/86680622
  16. @EnableEurekaClient //启用服务注册与发现
  17. public class WebApplication { //extends SpringBootServletInitializer
  18. public static void main(String[] args){
  19. SpringApplication.run(WebApplication.class,args);
  20. }
  21. }

测试

启动项目 test-invoice-eureka
启动项目 test-invoice-service
启动项目 test-invoice-web

启动多个项目参考

启动多个项目

首先访问 http://localhost:8772/ ,看 Instances currently registered with Eureka 是否能看到

test-invoice-service 项目
test-invoice-web 项目

测试-Add

使用 Postman 访问 http://localhost:8080/enta/api/Inv/Api/Test/Add

参数

  1. {"id":"","name":"luoma","version":"1.0.6"}

结果

测试-Update

使用 Postman 访问 http://localhost:8080/enta/api/Inv/Api/Test/Update

参数

  1. {"id":"11d1dd6b2bbe1d9a729986f5c2f62b42","name":"测试数据-菲克-1","version":"1.0.1"}

结果

测试-Del

使用 Postman 访问 http://localhost:8080/enta/api/Inv/Api/Test/Del?name=luoma&version=1.0.1

结果

测试-Get

使用 Postman 访问 http://localhost:8080/enta/api/Inv/Api/Test/Get

参数

  1. {"id":"","name":"测试数据-菲克-1","version":""}

测试-Query

使用 Postman 访问 http://localhost:8080/enta/api/Inv/Api/Test/Query

参数

  1. {"page":2,"pageSize":3,"name":"luoma"}

项目开发过程中遇到的问题及解决

创建包重复问题

父模块 pom.xml 引入包子模块 pom.xml 无法解析问题

访问接口-提示 Unsupported Media Type

启动 Spring Boot 项目访问接口提示 Login with Username and Password

无法构造’com.baomidou.mybatisplus.core.metadata.ipage’的实例

项目总类图

项目总结构图

扩展-负载均衡

创建子模块-test-invoice-service-1

test-invoice-cloud 上右键,新建模块

左侧面板选择 Maven,不勾选 Create from archetype 选项,如下图,点击 下一个 即可。

artifactId test-invoice-service-1

模块名称 test-invoice-service-1

复制 test-invoice-service 模块的所有内容到 test-invoice-service-1

修改启动类为 ServerApplication_1

  1. package com.test.invoice;
  2. import org.activiti.spring.boot.SecurityAutoConfiguration;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /**
  8. * 启动类
  9. *
  10. * @author:
  11. * @version:
  12. * @date: 2019-08-12 09:53
  13. */
  14. @SpringBootApplication(exclude = SecurityAutoConfiguration.class) //禁用 security 验证
  15. @RestController
  16. @EnableEurekaClient //Eureka Client
  17. public class ServerApplication_1 {
  18. public static void main(String[] args){
  19. SpringApplication.run(ServerApplication_1.class,args);
  20. }
  21. }

修改 TRbtTestServiceImpl 的 Add 方法

Add 方法添加代码 data.setName(data.getName()+"_18801"); 以示区分

  1. @Override
  2. public ResponseVO<String> Add(@RequestBody TRbtTestData data){
  3. data.setName(data.getName()+"_18801");
  4. TRbtTestEntity entity = new TRbtTestEntity();
  5. entity.setName(data.getName()).setVersion(data.getVersion());
  6. if(baseMapper.insert(entity) > 0){
  7. return new ResponseVO<>(ResponseCode.OK);
  8. }
  9. return new ResponseVO<>(ResponseCode.OPERATE_ERROR,"ERROR");
  10. }

修改 application.yml 端口号

端口号从 18800 修改为 18801,其它不变

  1. server:
  2. port: 18801
  3. spring:
  4. profiles:
  5. active: dev # 指定配置文件
  6. http:
  7. encoding:
  8. force: true # 默认编码,即 utf8
  9. activiti:
  10. check-process-definitions: false # 校验流程文件,默认校验resources下的processes文件夹里的流程文件
  11. # 服务名称,即serviceId
  12. application:
  13. name: service-producer
  14. sleuth:
  15. web:
  16. client:
  17. enabled: true # 启用为分布式web client 客户端
  18. sampler:
  19. probability: 1.0 # 将采样比例设置为 1.0,也就是全部都需要。默认是 0.1

启动项目

依次启动

  1. 启动项目 `test-invoice-eureka`
  2. 启动项目 `test-invoice-service`
  3. 启动项目 `test-invoice-service-1`
  4. 启动项目 `test-invoice-web`

查看 Eureka 是否注册

访问 http://localhost:8772/

使用 Postman 调用接口

快速的多次点击添加

URL:http://localhost:8080/enta/api/Inv/Api/Test/Add
参数:{"id":"","name":"五哥","version":"1.0.6"}

数据库查询结果

  1. SELECT * FROM `t_rbt_test`
  2. where name like '五哥%'

可以看到有些是正常的数据,有些是带后缀 _18801 的数据

说明两个服务中心 test-invoice-servicetest-invoice-service-1 自动提供了服务均衡负载的功能

项目调用关系图


相关附件 test-invoice-cloud | 大小:0.1M | 下载 test-invoice-cloud-负载均衡 | 大小:0.13M | 下载