summary
maven micro service project is divided into several different services according to different businesses;
Dependency inheritance
Project initial creation
If you are learning, you can look at the new reference. Otherwise, you can directly download the source code and simply modify and practice after the trial run. There is a code generator, which can generate basic code according to the database.
1, Create project guli
Create a new folder under the working directory guli
Select File - Open in idea and select this folder
2, Create parent project Guli framework parent
1. Create parent project
Create a module under the project guli: quickly initialize a Spring Boot module using Spring Initializr, version: 2.0.7.RELEASE
2. Delete src directory
3. Configure pom.xml
Modified version: 2.0.7.RELEASE
Add after node
<packaging>pom</packaging>
to configure
<properties> <java.version>1.8</java.version> <guli.version>0.0.1-SNAPSHOT</guli.version> <mybatis-plus.version>3.0.5</mybatis-plus.version> <velocity.version>2.0</velocity.version> <swagger.version>2.7.0</swagger.version> <aliyun.oss.version>2.8.3</aliyun.oss.version> <jodatime.version>2.10.1</jodatime.version> <poi.version>3.9</poi.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <commons-io.version>2.6</commons-io.version> <httpclient.version>4.5.1</httpclient.version> <gson.version>2.8.2</gson.version> <jwt.version>0.7.0</jwt.version> <aliyun-java-sdk-core.version>4.3.3</aliyun-java-sdk-core.version> <aliyun-sdk-oss.version>3.1.0</aliyun-sdk-oss.version> <aliyun-java-sdk-vod.version>2.15.0</aliyun-java-sdk-vod.version> <aliyun-sdk-vod-upload.version>1.4.5</aliyun-sdk-vod-upload.version> <fastjson.version>1.2.28</fastjson.version> <json.version>20170516</json.version> </properties>
Configuration lock dependent version
<dependencyManagement> <dependencies> <dependency> <groupId>com.guli</groupId> <artifactId>guli-framework-common</artifactId> <version>${guli.version}</version> </dependency> <!--mybatis-plus Persistent layer--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- velocity template engine, Mybatis Plus Code generator needs --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>${velocity.version}</version> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <!--swagger ui--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency> <!--aliyunOSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>${aliyun.oss.version}</version> </dependency> <!--Date time tool--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${jodatime.version}</version> </dependency> <!--xls--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <!--xlsx--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <!--File upload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!--Spring Cloud--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR2</version> <type>pom</type> <scope>import</scope> </dependency> <!--commons-io--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!--gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson.version}</version> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>${jwt.version}</version> </dependency> <!--aliyun--> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>${aliyun-java-sdk-core.version}</version> </dependency> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>${aliyun-sdk-oss.version}</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-vod</artifactId> <version>${aliyun-java-sdk-vod.version}</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-sdk-vod-upload</artifactId> <version>${aliyun-sdk-vod-upload.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>${json.version}</version> </dependency> </dependencies> </dependencyManagement>
3, Create module Guli framework common
1. Create module
Create a normal maven module
Parent: guli-framework-parent
Artifact: guli-framework-common
2. Configure pom.xml
Configure dependencies
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <optional>true</optional> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <optional>true</optional> </dependency> <!--lombok Used to simplify entity classes: need to install lombok plug-in unit--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <optional>true</optional> </dependency> <!--xls--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <optional>true</optional> </dependency> <!--xlsx--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <optional>true</optional> </dependency> </dependencies>
4, Create module Guli microservice edu
Import database
Data script: guli_edu.sql
1. Create module
Create a normal maven module
Parent: guli-framework-parent
Artifact: guli-microservice-edu
2. Configure pom.xml
<dependencies> <dependency> <groupId>com.guli</groupId> <artifactId>guli-framework-common</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- velocity template engine, Mybatis Plus Code generator needs --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency> <!--lombok Used to simplify entity classes: need to install lombok plug-in unit--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--xls--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> <!--Developer Tools--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
3. Configure the application.properties file
Create the file application.properties in the resources directory
# Service port server.port=8110 # service name spring.application.name=guli-edu # Environment settings: dev, test, prod spring.profiles.active=dev # mysql database connection spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/guli_edu?characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=123456 # Hikari is the default consolidated database connection pool after Spring Boot 2.0, which is faster than druid # Data source type spring.datasource.type=com.zaxxer.hikari.HikariDataSource # Connection pool name, default HikariPool-1 spring.datasource.hikari.pool-name=GuliHikariPool # The maximum number of connections, less than or equal to 0, will be reset to the default value of 10; Greater than zero and less than 1 will be reset to the value of minimum idle spring.datasource.hikari.maximum-pool-size=12 # Connection timeout: ms, less than 250 ms, otherwise it will be reset to the default value of 30 seconds spring.datasource.hikari.connection-timeout=60000 # The minimum idle connection is 10 by default. If it is less than 0 or greater than maximum pool size, it will be reset to maximum pool size spring.datasource.hikari.minimum-idle=10 # Idle connection timeout, the default value is 600000 (10 minutes). If it is greater than or equal to Max lifetime and Max lifetime > 0, it will be reset to 0; If it is not equal to 0 and less than 10 seconds, it will be reset to 10 seconds. # Only when the number of idle connections is greater than the maximum number of connections and the idle time exceeds this value will it be released spring.datasource.hikari.idle-timeout=500000 # The maximum connection lifetime. If it is not equal to 0 and less than 30 seconds, it will be reset to the default value of 30 minutes. The setting should be shorter than the timeout set by mysql spring.datasource.hikari.max-lifetime=540000 #Connection test query spring.datasource.hikari.connection-test-query=SELECT 1 #mybatis log mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4. Create MP code generator
Create the package com.guli.edu in the test/java directory and create the code generator: CodeGenerator.java
package com.guli.edu; public class CodeGenerator { @Test public void genCode() { String moduleName = "edu"; // 1. Create code generator AutoGenerator mpg = new AutoGenerator(); // 2. Global configuration GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("Helen"); gc.setOpen(false); //Open Explorer after build gc.setFileOverride(false); //Whether the file is overwritten during regeneration gc.setServiceName("%sService"); //Remove the initial I of the Service interface gc.setIdType(IdType.ID_WORKER_STR); //Primary key policy gc.setDateType(DateType.ONLY_DATE);//Defines the date type in the generated entity class gc.setSwagger2(true);//Turn on Swagger2 mode mpg.setGlobalConfig(gc); // 3. Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/guli_" + moduleName); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); // 4. Package configuration PackageConfig pc = new PackageConfig(); pc.setModuleName(moduleName); //Module name pc.setParent("com.guli"); pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // 5. Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setInclude(moduleName + "_\\w*");//Set the table name to map strategy.setNaming(NamingStrategy.underline_to_camel);//Naming policy for mapping database tables to entities strategy.setTablePrefix(pc.getModuleName() + "_");//Set table prefix not to generate strategy.setColumnNaming(NamingStrategy.underline_to_camel);//Naming policy for mapping database table fields to entities strategy.setEntityLombokModel(true); // lombok model @ accessories (chain = true) setter chain operation strategy.setLogicDeleteFieldName("is_deleted");//Delete field name logically strategy.setEntityBooleanColumnRemoveIsPrefix(true);//Remove Boolean is_ prefix //Auto fill TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); strategy.setVersionFieldName("version");//Optimistic lock column strategy.setRestControllerStyle(true); //restful api style controller strategy.setControllerMappingHyphenStyle(true); //Hump to hyphen in url mpg.setStrategy(strategy); // 6. Execute mpg.execute(); } }
Execute code generator method
explain:
XxxServiceImpl inherits the ServiceImpl class, and MP injects xxmapper for us
In this way, we can use many methods provided by the service layer by default. Of course, we can also call our own methods written in the dao layer.
5. Modify entity
Add comments to the Teacher.java deleted field
@TableField(value = "is_deleted")
Add comments to the Video.java free field
@TableField(value = "is_free")
6. Write background management api interface
Create the admin package under the controller package and create TeacherAdminController.java
package com.guli.edu.controller.admin; @RestController @RequestMapping("/admin/edu/teacher") public class TeacherAdminController { }
Get a list of all instructors
@Autowired private TeacherService teacherService; @GetMapping public List<Teacher> list(){ return teacherService.list(null); }
7. Create SpringBoot configuration file
Create the config package under the edu package and create MyBatisPlusConfig.java
package com.guli.edu.config; @Configuration @EnableTransactionManagement @MapperScan("com.guli.edu.mapper") public class MyBatisPlusConfig { }
Configure related plug-ins
/** * SQL Execute performance analysis plug-in * It is not recommended to use the development environment online. maxTime refers to the maximum sql execution time */ @Bean @Profile({"dev","test"})// Set dev test environment on public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(1000);//ms. if the ms set here is exceeded, sql will not be executed performanceInterceptor.setFormat(true); return performanceInterceptor; } /** * Logical delete plug-in */ @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); } /** * Paging plug-in */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
8. Create a SpringBoot startup class
Create config package under edu package and EduApplication.java
package com.guli.edu; @SpringBootApplication public class EduApplication { public static void main(String[] args) { SpringApplication.run(EduApplication.class, args); } }
9. Run startup class
visit http://localhost:8110/admin/edu/teacher Get json data
10. Unified returned json time format
By default, json time format has time zone and is world standard time, which is eight hours away from our time
Set in application.properties
#Returns the global time format of json spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8
4, Logical deletion
1. TeacherAdminController add delete method
@DeleteMapping("{id}") public boolean removeById(@PathVariable String id){ return teacherService.removeById(id); }
2. Test deletion using postman
Test after restarting edu project
http://localhost:8110/admin/edu/teacher/1
Test result: the delete field in the database is set to 1
5, Cross domain configuration
1. What is cross domain
When a browser requests the resources of another domain name from the web page of one domain name, the domain name, port and protocol are all cross domain. In the development of front-end and back-end separation, we need to consider the problem of ajax cross domain.
Here we can solve this problem from the server
2. Disposition
Add annotation on Controller class
@CrossOrigin //Cross domain
maven dependency management
Dependent inheritance
Transmission since
Parent project:
Inherited by other subprojects dependencyManagement Management version,The corresponding dependencies will not be downloaded to maven The warehouse must be configured if there are the same dependencies in the subproject dependencies Unified dependency management, and the corresponding dependencies will be downloaded to maven Warehouse. If there are the same dependencies in the subproject, it does not need to be configured
General tools project
Dependent on other subprojects dependencies Manage dependencies for the current project
Subproject
dependencies Manage dependencies, and the corresponding dependencies will be downloaded to maven Warehouse Dependent inheritance Inherit from parent project dependencies Dependency management under node Dependent delivery If the current project depends on a generic tool project, the dependencies under the generic tool project will also be passed to the current project