Building the first distributed project

I. create project guli

Create a new folder in the working directory guli

Select File - Open in idea and select this folder

II. Create a Guli framework parent

1. Create parent project

Create module under project guli: use spring initializer to quickly initialize a Spring Boot module, version: 2.0.7.RELEASE

2. Delete src directory

Modified version: 2.0.7.RELEASE

Add after < artifactid > node

<packaging>pom</packaging>

Configure < Properties >

<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>

Configure < dependencymanagement > to lock dependent versions

<dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>com.guli</groupId>
            <artifactId>guli-framework-common</artifactId>
            <version>${guli.version}</version>
        </dependency>

        <!--mybatis-plus Persistence 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 requires -->
        <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>

III. 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 To simplify entity classes: installation required 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>

IV. create Guli microservice edu module

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 requires -->
    <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 To simplify entity classes: installation required 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 250ms, otherwise reset to the default value of 30s
spring.datasource.hikari.connection-timeout=60000
# Minimum free connection, default value 10, less than 0 or greater than maximum pool size, will be reset to maximum pool size
spring.datasource.hikari.minimum-idle=10
# Idle connection timeout, the default value is 600000 (10 minutes), greater than or equal to Max lifetime and Max lifetime > 0, will be reset to 0; not equal to 0 and less than 10 seconds, 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 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 package com.guli.edu under test/java directory, and create 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 when rebuilding
        gc.setServiceName("%sService");	//Remove the initial I from the Service interface
        gc.setIdType(IdType.ID_WORKER_STR); //Primary key policy
        gc.setDateType(DateType.ONLY_DATE);//Define the date type in the generated entity class
        gc.setSwagger2(true);//Switch 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 strategy of database table mapping to entity
        strategy.setTablePrefix(pc.getModuleName() + "_");//Set table prefix not generated

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//The naming policy of database table field mapping to entity
        strategy.setEntityLombokModel(true); // lombok model @ Accessors(chain = true) setter chain operation

        strategy.setLogicDeleteFieldName("is_deleted");//Logical deletion field name
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//Remove the is prefix of the Boolean value

        //Automatic 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 list

        strategy.setRestControllerStyle(true); //restful api style controller
        strategy.setControllerMappingHyphenStyle(true); //Camel to hyphen in url

        mpg.setStrategy(strategy);

        // 6, implementation
        mpg.execute();
    }
}

Execute code generator method

Explain:

XxxServiceImpl inherits ServiceImpl class, and MP injects XxxMapper for us

In this way, we can use many methods provided for us by the service layer by default, and of course, we can also call our own methods written in the dao layer.

5. Modify entity

Annotate the Teacher.java deleted field

@TableField(value = "is_deleted")

Annotate the Video.java free field

@TableField(value = "is_free")

6. Write the background management api interface

Create the admin package under the controller package, and create the 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 a SpringBoot configuration file

Create config package under edu package and MyBatisPlusConfig.java

package com.guli.edu.config;

@Configuration
@EnableTransactionManagement
@MapperScan("com.guli.edu.mapper")
public class MyBatisPlusConfig {
    
}

Configure related plug-ins

/**
     * SQL Perform performance analysis plug-in
     * It is not recommended for use in development environment. maxTime refers to the maximum execution time of sql
     */
@Bean
@Profile({"dev","test"})// Set the 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 execute.
    performanceInterceptor.setFormat(true);
    return performanceInterceptor;
}

/**
      * Logical removal plug-in
      */
@Bean
public ISqlInjector sqlInjector() {
    return new LogicSqlInjector();
}

/**
     * Paging plugins
     */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

8. Create a SpringBoot startup class

Create config package and EduApplication.java under edu package

package com.guli.edu;

@SpringBootApplication
public class EduApplication {

    public static void main(String[] args) {
        SpringApplication.run(EduApplication.class, args);
    }
}

9. Operation and startup

Visit http://localhost:8110/admin/edu/teacher Get json data

10. Unified return json time format

By default, the json time format has a time zone and is world standard time, eight hours behind 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

IV. logical deletion

1. TeacherAdminController add / delete method

@DeleteMapping("{id}")
public boolean removeById(@PathVariable String id){
    return teacherService.removeById(id);
}

2. Use postman test to delete

Test after restarting edu project

 

V. cross domain configuration

1. What is cross domain

When a browser requests resources of another domain name from a domain name's web page, any difference in domain name, port, and protocol is 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, configuration

Add annotation on Controller class

@CrossOrigin //Cross domain

 

 

 

 

 

 

 

 

 

 

Keywords: Spring Java SDK Mybatis

Added by BostonMark on Sun, 27 Oct 2019 10:09:11 +0200