当前位置:网站首页>Microservice system design - sub service project construction
Microservice system design - sub service project construction
2022-06-24 18:37:00 【Zhuangxiaoyan】
Abstract
After the early demand analysis, model design and system architecture design , We have a clearer understanding of the overall structure of the project , The rest of the work is based on the design , Pull out the project skeleton , Fill it with flesh and blood . Build sub micro service modules in the system .
One 、 Build the skeleton of the whole project
The agreed project name is parking-project , establish Maven project ,packaging The way by pom, Used to manage all modules . stay parking-project Under the project, it is established according to the functional modules maven module subprojects . use IDE Tools . With Maven Project Form to create the parent project , Used to manage sub module functions .


You can see , The sub module will automatically parent project Set to parking-project Parent project . Because of the adoption of Spring Boot To build subprojects , Choose... Here packaging The way is jar . According to this, each sub module can be created continuously , The final result is as follows :

Briefly introduce the functions of each module :
- parking-base-serv,pom project , It contains two sub modules :parking-admin,parking-gateway.
- parking-admin, Monitor the operation of sub projects .
- parking-gateway, Gateway sub service , coordination JWT Implement conversation 、 Functions such as power verification .
- parking-carwash, Car washing service , Connect park-carwash database .
- parking-card, Points sub service , Connect park-card database .
- parking-charging, Billing sub service , Connect parking-charging The repository
- parking-finance, Financial sub services , Connect parking-finance The repository .
- parking-member, Member subservices , Connect park-member The repository .
- parking-resource, Resource sub services , Connect park-resource The repository .
- parking-message, Message sub service , Connect park-message The repository , together with rocketmq Store message data
- parking-common, Store common utility classes , Physical packages and so on .
Two 、 Create a member sub service
2.1 introduce spring-boot-starter-parent rely on
Each sub module is a Spring Boot project , If introduced in a sub module , It will cause a lot of repetitive work , And the version should not be maintained uniformly , Prone to multiple versions of confusion , therefore Spring Boot The version of requires global unified maintenance . Each subproject needs to be built into jar File run , The child project already depends on the configuration of the parent project , Each subproject pom.xml Files have such dependencies :
<parent>
<groupId>com.mall.parking.root</groupId>
<artifactId>parking-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>If in the usual way , Reuse parent Mode introduction spring-boot-starter-parent rely on , Obviously against a single pom There is only one... In the document parent Standard of label , Compilation will fail .
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>To solve this problem , Here the parking-project The parent project is marked with depencyMangement Mode introduction spring-boot-starter-parent, Subprojects depend on parent The parent configuration is OK .
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>There are small partners who may propose directly in the root project pom use parent Way to introduce , The sub modules pass directly through maven Rely on it , This mode operates independently Spring Boot There is no problem with the project . The following is introduced in the same way Spring Cloud or Spring Cloud Alibaba , One parent Labels obviously don't meet this need , use dependencyManagement Can avoid this problem .
2.2 introduce MBG plug-in unit
MBG Plug ins can be generated automatically mapper Interface 、mapper xml To configure 、 Corresponding entity classes , The main function is to develop rapidly , Eliminate unnecessary coding .
stay pom Configuration dependency in MBG Plug in for :
<build>
<finalName>parking-member-service</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<!-- mybatis Configuration files for generating code -->
<configurationFile>src/test/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>stay src/test/resource Write to generatorConfig.xml file , To configure MBG plug-in unit Basic configuration items required .
<generatorConfiguration>
<!-- Local mysql Driving position -->
<classPathEntry location="/Users/apple/.m2/repository/mysql/mysql-connector-java/5.1.42/mysql-connector-java-5.1.42.jar" />
<context id="mysqlTables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/park-member?useUnicode=true" userId="root"
password="root">
<property name="useInformationSchema" value="true"/>
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Generate model Entity class file location -->
<javaModelGenerator targetPackage="com.mall.parking.member.entity" targetProject="src/test/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- Generate mapper.xml Profile location -->
<sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/test/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Generate mapper Interface file location -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.mall.parking.member.mapper" targetProject="src/test/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- The table name corresponding to the entity class to be generated , Multiple entity classes can copy multiple copies of this configuration -->
<table tableName="member" domainObjectName="Member">
<generatedKey column="tid" sqlStatement="SELECT REPLACE(UUID(), '-', '')"/>
</table>
<table tableName="vehicle" domainObjectName="Vehicle">
<generatedKey column="tid" sqlStatement="SELECT REPLACE(UUID(), '-', '')"/>
</table>
<table tableName="month_card" domainObjectName="MonthCard">
<generatedKey column="tid" sqlStatement="SELECT REPLACE(UUID(), '-', '')"/>
</table>
</context>
</generatorConfiguration>When the configuration is complete , In the project name ” parking-member “ Right click , Select from the pop-up menu " Run As " —>" Maven build… ", stay Goals Enter the following command in the column :
mybatis-generator:generateAfter the command is executed successfully , Find the corresponding file in the corresponding directory , Then copy To src/java In the corresponding directory , then test Delete the generated files in the directory .
- 1.4 pre-release ,MBG Plug in generated xml file , It's the append mode , Instead of covering , Easy to form repeated labels .
- MBG It doesn't generate controller/service Layer related code , It needs to be done manually .
2.3 introduce Lombok, Simplify the code
Because the compilation phase will use lombok, So you need to be in IDE Install in lombok plug-in unit , To compile normally .
2.4 Log notes
If you don't want to write every time , You can annotate @sl4j To print logs .
private final Logger logger = LoggerFactory.getLogger( The name of the class .class);2.5 introduce MyBatis rely on
More efficient introduction MyBatis, Here the starter Way to introduce , Also at the root pom.xml Maintain component versions in files .
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>stay application.properties Set the database connection in the configuration file ,Spring Boot 2.x The default version is HikariCP As JDBC Connection pool .
mybatis.type-aliases-package=com.mall.parking.member.entity
# If it needs to be replaced Druid Connection pool , The following configuration items need to be added :
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#use new driver replace deprecated driver:com.mysql.jdbc.Driver.
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/park_member?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = rootsend mapper Interface files can be scanned by the system , Pass... In the main class @mapperscan annotation , Or directly in mapper Add... To the interface file @mapper annotation .
2.6 Test whether the framework is successful
@RestController
@RequestMapping("member")
@Slf4j
public class MemberController {
@Autowired
MemberService memberService;
@RequestMapping("/list")
public List<Member> list() {
List<Member> members = memberService.list();
log.debug("query member list = " + members);
return members;
}
}
MemberServiceImpl Implementation class
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
MemberMapper memberMapper;
@Override
public List<Member> list() {
MemberExample example = new MemberExample();
List<Member> members = memberMapper.selectByExample(example);
return members;
}
}Start project , Show success log after success :
2019-12-30 16:45:13.496 INFO 9784 --- [ main] c.mall.parking.member.MemberApplication : Started MemberApplication in 6.52 seconds (JVM running for 7.753)open Postman plug-in unit , Test whether the method is normal , The operation is as follows :

2.7 Multi environment configuration
The daily product development inevitably involves the problem of multi deployment , For example, development environment 、 Test environment 、 Production environment, etc , This requires that code deployment can meet the requirements of multiple environments . Through manual modification , Not only is it easy to make mistakes , It will also waste labor costs , Must be combined with automated builds to improve accuracy .Spring Boot Provides the basis for profile Multi environment configuration , Multiple configuration files can be added to each microservice item , Such as
- application.properties/yml Basic public configuration
- application-dev.properties/yml Development environment configuration
- application-test.properties/yml Test environment configuration
- application-pro.properties/yml Production environment configuration
In the public profile application.properties in , By configuring spring.profiles.active = dev To determine which configuration to enable , Or when starting the build package , Add commands to activate different environment configurations : java -jar parking-member.jar --spring.profiles.active=dev thus , The first is simple Spring Boot Module construction is completed , The next step will be park-member The normal business function coding of the module can be completed .
Blog reference
边栏推荐
- [untitled]
- Recommend 14 commonly used test development tools
- Common MySQL commands of installation free version
- 696. count binary substring
- What are the reasons for the abnormal playback of the online channel of the channel accessed by easycvr national standard protocol?
- Eight digit
- Skills of writing test cases efficiently
- 130. surrounding area
- 微服务系统设计——数据模型与系统架构设计
- 13 ways to reduce the cost of cloud computing
猜你喜欢

Network security database penetration of secondary vocational group in 2022

SAP license: what is ERP supply chain

Sudoku (easy to understand)

Architecture decryption from distributed to microservice: several common microservice architecture schemes

110. balanced binary tree

Different JVM

(Video + graphics) introduction to machine learning series - Chapter 11 support vector machines

Business leaders compete for CIO roles

696. count binary substring

High quality defect analysis: let yourself write fewer bugs
随机推荐
How to start cloud native application development
Selection (032) - what is the output of the following code?
Uniapp wechat applet calls mobile map to navigate to the target point
What if the database table structure changes? Smartbi products support one click synchronization
R language Quantitative Ecology redundancy analysis RDA analysis plant diversity species data visualization
Usage of typedef enum (enumeration)
Huitongda officially landed at the Hong Kong Stock Exchange: the gross profit margin continued to decline, and the book value of several shareholders still suffered losses
Redpacketframe and openmode packages
How about China Power Investment Xianrong futures? Is it safe to open futures accounts?
How MySQL works - Chapter 14
Millions of dollars worth of NFT were stolen in the attack, and Google issued an emergency warning to 3.2 billion users worldwide | February 21 global network security hotspot
Exception: Gradle task assembleDebug failed with exit code 1
Implementation of pure three-layer container network based on BGP
Complete Guide to web application penetration testing
Leetcode daily question solution: 717 1-bit and 2-bit characters - reverse order
What is business intelligence (BI)?
Easygbs video platform TCP active mode streaming exception repair
Four security issues of low code and no code development
JS string method
[NLP] 3 papers on how Stanford team builds a better chat AI