当前位置:网站首页>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
边栏推荐
- 130. surrounding area
- Selection (031) -cool_ How long can secret be accessed?
- Eight recommended microservice testing tools
- Vite+web3:报错出现ReferenceError: process is not defined
- Application service access configuration parameters
- Skills of writing test cases efficiently
- Three indicators to help you measure the effectiveness of digital transformation
- Nacos cluster starts throwing set of SQL_ SELECT_ LIMIT is not support
- Wechat applet to realize stacked rotation
- [NLP] 3 papers on how Stanford team builds a better chat AI
猜你喜欢
What if the database table structure changes? Smartbi products support one click synchronization

SAP license: what is ERP supply chain

What is decision intelligence?

Vite+web3:报错出现ReferenceError: process is not defined
![717.1-bit and 2-bit characters [sliding window]](/img/61/449566d2a8efbd403ae0361f839683.jpg)
717.1-bit and 2-bit characters [sliding window]

How does the chief information security officer discuss network security with the enterprise board of directors

Flutter dart regular regexp matches non printing characters \cl\cj\cm\ck

Graph traversal (BFS and DFS) C language pure handwriting

Mcu-08 interrupt system and external interrupt application

Top ten popular codeless testing tools
随机推荐
Some knowledge of the beginning of 2022
DOM (document object model)
Leetcode topic [array] -216- combined sum III
Easynvr fails to use onvif to detect the device. What is the reason why "no data" is displayed?
股票网上开户安全吗?应该怎么办理?
Leetcode question 136 [single number]
Mcu-08 interrupt system and external interrupt application
Why are more and more people studying for doctors? Isn't it more and more difficult to graduate a doctor?
Business based precipitation component = & gt; manage-table
2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)
Why should state-owned enterprises accelerate the digital transformation
Regression testing strategy for comprehensive quality assurance system
Bisection function template
Get max value of a bit column - get max value of a bit column
Ten excellent business process automation tools for small businesses
Easygbs video platform TCP active mode streaming exception repair
Six configuration management tools that administrators must know
SAP license: ERP for supply chain management and Implementation
Does the wave of layoffs in Chinese enterprises in 2021 need to be "judged" by morality?
Two micro service interviews where small companies suffer losses