- 微服务容器化开发实战
- 尹为强
- 1329字
- 2025-02-28 05:18:02
2.4 编写框架代码
如果使用Spring Cloud“全家桶”构建项目的微服务框架,则可以使用EUREKA、Zuul、Config、Hystrix、Zipkin和Ribbon等组件。EUREKA用于服务注册与发现,Zuul用于网关与路由,Config用于统一配置,Hystrix用于熔断器,Zipkin用于调用链跟踪,Ribbon用于客户端调用的负载均衡。Spring Cloud各组件的详细介绍与使用读者可自行学习,此处不再赘述。
笔者的生产项目没有使用Spring Cloud微服务框架全套组件,而是结合微服务运行环境Kubernetes进行了取舍,选取了Zuul、Hystrix和Zipkin,而服务注册与发现则使用Kubernetes的服务发现与注册来代替,使用Spring Boot Security和JWT进行角色与权限控制。
2.4.1 创建Maven工程
创建一个Maven工程,目录名称为ecs-order-system,项目名称为eos-parent。该项目是父项目,后续各个微服务为其子项目(子模块)。下面对eos-parent项目的pom.xml文件进行解析。
(1)父项目定义,具体如下:

定义eos-parent父项目的groupId、artifactId和版本号version。
(2)JDK版本定义,具体如下:

定义eos-parent父项目及其子模块都是基于JDK1.8进行编辑和编译的。
(3)Spring Boot版本定义,具体如下:

定义将Spring Boot 1.5.13版本作为开发环境和运行环境。
(4)Spring Cloud版本定义,具体如下:

定义将Spring Cloud Edgware.SR4版本作为开发和运行环境。
(5)Maven编译插件定义,具体如下:

定义使用Spring Boot的Maven插件进行微服务编译和打包。
(6)微服务公共依赖定义,具体如下:

微服务子模块的公共依赖定义包括RESTful API开发、熔断和调用链等需要依赖的包,版本号继承使用Spring Boot和Spring Cloud定义的版本即可,这些公共依赖定义在dependencies内部。
2.4.2 创建微服务模块
父项目设置完成后,需要创建各个微服务的子模块,单击父项目,选择“File/New”菜单中的“Module”命令,弹出的对话框如图2-6所示。

图2-6 创建微服务模块(一)
单击“Next”按钮,设置模块的GroupId、ArtifactId和Version,如图2-7所示。

图2-7 创建微服务模块(二)
如图2-7所示,子模块的GroupId和Version可以继承父项目。ArtifactId是微服务名称,一般采用“xxxx-xxxx-xxxx”的三段式命名规则,可以命名为“公司-产品-模块”。笔者参与的项目没有命名公司,而是从部门产品系统开始的,如eos-order-verify和eos-system-setting分别表示订单审核与系统设置微服务。
添加微服务子模块后,在父项目的pom.xml文件中会添加一个模块module,具体如下:

2.4.3 微服务代码结构
框架代码包括父项目和各子模块的代码结构与基本配置,在IDEA中,微服务eos-order-account的代码目录结构如图2-8所示。

图2-8 微服务eos-order-account的代码目录结构
配置文件包括Maven的pom.xml文件和Spring Boot的bootstrap.yml、application-dev.yml、application-prod.yml、application-test.yml。Java代码包括Spring Boot启动入口的OrderAccountApplication.java,以及Spring Boot开发的基本源代码目录controller、mapper、service等。
下面对各文件和目录进行详细介绍。
1.pom.xml文件
该段代码配置的关键是parent配置项,完整配置如下所示:

微服务的Maven配置pom.xml文件,使用parent设置继承父项目配置,同时设置自己的artifactId。
2.Spring Boot配置文件
微服务使用Spring Boot进行开发,配置文件包括application-dev.yml、application-prod.yml、application-test.yml、bootstrap.yml。其中,application-*.yml是运行在开发、测试和生产环境中的特殊配置,bootstrap.yml是微服务启动后首先加载的配置文件。
bootstrap.yml配置一般是固定不变的,如微服务名称、端口等;而application-*.yml配置是随运行变化而变化的,如数据库地址、redis地址、第三方接口地址、日志输出目录等。
application-dev.yml配置如下(节选):

application-prod.yml配置如下(节选):

bootstrap.yml配置如下:

此处没有展示application-test.yml配置的内容,从application-dev.yml配置和application-prod.yml配置来看,主要是日志目录、数据库地址、redis地址等随运行环境不同而需要分开配置。
3.微服务入口文件
微服务入口的代码格式主要包括几个注解和main()函数,如下所示:

包含main()函数的OrderAccountApplication.java文件就是微服务eos-order-account的入口,引入Spring Boot启动注解@SpringBootApplication,需要注意的是,注解@EnableCircuitBreaker是熔断器使用的,后续章节会详细介绍。