Spring Boot(2)

1. Operation and maintenance

1.1. Packaging program

The SpringBoot program is created based on Maven, and Maven provides packaging instructions called packages. This operation can be performed in the Idea environment.

mvn package

After packaging, a jar file with a similar project name will be generated, and its name is composed of module name + version number + .jar.

1.2, Program Run

After the program package is packaged, it can be executed directly. Execute the command in the path where the program package is located.

java -jar project package name.jar

After executing the program packaging instructions, the program runs normally, no different from executing the program under Idea.

Special attention: If your computer does not have a jdk environment for java installed, you will not be able to perform the above operations correctly, because the program execution uses java instructions.

Special attention: When using the wizard to create a SpringBoot project, there will be the following configuration in the pom.xml file. This configuration must not be deleted, otherwise the program will not be executed normally after packaging.

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

But there will actually be some other problems, such as loading the main boot class and the jdk version during packaging.

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                <mainClass>com.songzhishu.springboot.SpringBootDemo3Application</mainClass>
                <skip>false</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

If the port is occupied during startup, how to solve the problem?

# Query port
netstat -ano
#Query the specified port
netstat -ano |findstr "port number"
# Query the process name based on the process PID
tasklist |findstr "Process PID number"
# Kill tasks based on PID
taskkill /F /PID "Process PID number"
# Kill tasks based on process name
taskkill -f -t -im "process name"

2. Advanced configuration

2.1. Temporary attribute settings

After the program is packaged, some minor problems occur, and the configuration file needs to be modified. Then the program needs to be repackaged, and then the configuration file can be modified. Temporary attributes can be set when the program starts. The method is also very simple, just add the corresponding parameters when starting.

java –jar springboot.jar –-server.port=80

For example, modify the startup port number! Of course, you can also add other attributes. The above command is the command to start the SpringBoot package. After entering the command, leave a blank space and then enter two – signs. Just add the corresponding parameters in the form of attribute name = attribute value. Remember, the format here is not the writing format in yaml. When attributes have multi-level names, they are separated by dots, which is exactly the same as the attribute format in the properties file.

If you find that you want to modify more than one attribute, you can continue writing in the above format, using spaces to separate attributes.

java –jar springboot.jar –-server.port=80 --logging.level.root=debug

2.2, Attribute loading priority

Configuring and modifying attributes can not only be done through configuration classes, configuration files, temporary modifications, etc., there are actually 14 configuration locations officially provided, which means that if a certain configuration does not take effect, it is likely to be configured by another The place is covered

, and then you have to make modifications based on where these may appear!

2.3. Using temporary attributes in the development environment

It’s like this. Springboot provides the ability to temporarily modify properties. But what if you encounter a problem during actual development and need to temporarily modify properties, but the modification has no effect. Therefore, we must consider this issue during the re-development stage and we need to test it. Whether the configuration of the temporary environment can take effect.

In the boot class, args can be set with temporary attributes for testing. Of course, if you don’t want to modify the temporary attributes, just remove args.

2.4. Configuration file classification

SpringBoot provides configuration files and temporary properties to configure the program. What I have been talking about before is temporary attributes. This section will talk about configuration files. In fact, we have been using this configuration file, but we are using one of the four levels of configuration files provided by SpringBoot. The 4 levels are:

  • Configuration file under the classpath (I have always used this, which is the application.yml file in the resources directory)

  • Configuration file in the config directory under the classpath

  • Configuration file in the directory where the package is located

  • Configuration file in the config directory in the directory where the package is located

It’s so complicated, let’s talk about it one by one. In fact, the above four types of files provide you with the location where the four configuration files are written. Their functions are the same and they are all used for configuration. Then what everyone is concerned about is the difference. Yes, it is because of the difference in location. Generally speaking, if all four configuration files exist, there is a priority issue. To put it bluntly, if I add all four files, and they all have the same configuration, it is a matter of which one takes effect. The loading priority order of the above four files is

  1. file: config/application.yml [Highest]

  2. file:application.yml

  3. classpath:config/application.yml

  4. classpath: application.yml [Minimum]

3. Multi-environment development

What is multi-environment development is that different configuration files correspond to different environments.

3.1. Single configuration file

spring:
    config:
        activate: pro #Enable pro
---
spring:
    config:
        activate:
            on-profile: pro
server:
    port: 80
---
spring:
    config:
        activate:
            on-profile: dev
server:
    port: 81
---
spring:
    config:
        activate:
            on-profile: test
server:
    port: 82

Summary

  1. Multi-environment development requires setting up several common environments, such as development, production, and test environments

  2. Set multiple environments for use in yaml format—differentiate environment setting boundaries

  3. The difference between each environment is the configuration properties loaded.

  4. When enabling a certain environment, you need to specify that environment to be used at startup.

3.2. Multi-file configuration files

It is obviously unreasonable to put all configurations in one configuration file, especially since each configuration application scenario is different, so the idea of splitting one configuration file into multiple configuration files came up. After splitting, write its own configuration in each configuration file, and clearly indicate which configuration file to use in the main configuration file.

Main configuration file

spring:
    profiles:
        active: pro # Start pro

Environment configuration file

server:
    port: 80

Since each environment configuration file configures its own items, there is no need to write the name in it. The question is how to distinguish which set of configurations this is? Use file names to differentiate.

application-pro.yaml

server:
    port: 80

application-dev.yaml

server:
    port: 81

The naming rule of the file is: application-environment name.yml.

In the configuration file, if some configuration items are the same in all environments, these items can be written to the main configuration, and only the items that are different are written to the environment configuration file.

  • Set public configuration (global) in the main configuration file

  • Commonly used in environment classification configuration files to set conflict attributes (local)

Summary

  1. Environment properties can be defined using standalone configuration files

  2. Independent configuration files facilitate online system maintenance and updates and ensure system security

3.3. Skills in writing independent configuration files for multi-environment development

Preparation

Split the information in the configuration file according to functions and make all configurations into independent configuration files. The naming rules are as follows

  • application-devDB.yml

  • application-devRedis.yml

  • application-devMVC.yml

Use

Use the include attribute to load multiple environments at the same time to make them effective while activating the specified environment. Use commas to separate multiple environments.

spring:
    profiles:
        active:dev
        include: devDB,devRedis,devMVC

By comparison, now it is equivalent to loading the dev configuration and then loading the corresponding three sets of configurations. The structure is very clear. What is used and what are the corresponding names?

Note

When the main environment dev has the same attributes as other environments, the main environment attributes take effect; when other environments have the same attributes, the last loaded environment attributes take effect.

Improvements

But there is also a problem with the above settings. For example, when I want to switch the dev environment to pro, the include must also be modified. Because the include attribute can only be used once, this is more troublesome. SpringBoot uses the group attribute instead of the include attribute starting from version 2.4, reducing the amount of configuration writing. To put it simply, I write it first, and you can use whichever one you like.

spring:
    profiles:
        active:dev
        group:
            "dev": devDB,devRedis,devMVC
            "pro": proDB,proRedis,proMVC
            "test": testDB,testRedis,testMVC

Looking at it now, if I switch dev to pro, I only need to make a few changes and it’s over? Perfect!

Summary

  1. Multi-environment development uses the group attribute to set configuration file groups to facilitate online maintenance and management.

3.4. Multi-environment development control

We have basically finished talking about multi-environment development here, and finally let’s talk about the conflict issue. What to do if maven and SpringBoot set up multiple environments at the same time.

To deal with this conflict problem, you must first clarify the relationship between who has the dominant position in multi-environment development. In other words, if multiple environments are currently set up, whose environment should be retained and the other should follow the same settings.

What does maven do? It manages project construction and ultimately generates code packages. What does SpringBoot do? Simplified development. Simplification is not its leading role. In the end, it is still up to maven to manage the entire project, so SpringBoot should listen to maven. After the entire confirmation, the following is easy to do. The general idea is as follows:

  • First set the specific environment to use in the maven environment

  • Just read the environment set by maven in SpringBoot

Set multiple environments in maven

<profiles>
    <profile>
        <id>env_dev</id>
        <properties>
            <profile.active>dev</profile.active>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault> <!--Default startup environment-->
        </activation>
    </profile>
    <profile>
        <id>env_pro</id>
        <properties>
            <profile.active>pro</profile.active>
        </properties>
    </profile>
</profiles>

Read maven setting value in SpringBoot

spring:
profiles:
    active: @profile.active@

4. Log

4.1, log level

After the log is set up, you can choose which participation records are based on the settings. This is set according to the log level. There are 6 levels of logs, namely:

  • TRACE: Running stack information, low usage

  • DEBUG: used by programmers to debug code

  • INFO: Record operation and maintenance process data

  • WARN: Record operation and maintenance process alarm data

  • ERROR: Record error stack information

  • FATAL: disaster information, merged into ERROR

Under normal circumstances, use DEBUG during development, use INFO after going online, and use WARN to record operation and maintenance information. Next, set the log level. Those with lower log levels will be overwritten by those with higher log levels.

logging:
    # Set log group
    group:
        # Customize the group name and set the packages included in the current group
        ebank: com.songzhishu.controller
    level:
        root: warn
        #Set the log level for the corresponding group
        ebank:debug
        # Set the log level for the package
        com.songzhishu.controller: debug

Quickly add log objects to classes based on the @Slf4j annotation provided by lombok

4.2. Log output format control

Logs can already be recorded, but the current recording format is provided by SpringBoot. If you want to customize the control, you need to set it yourself. First analyze the current log recording format.

2023-11-10 12:43:06.694 #time
INFO #Log level
2024 #pid
---
[main] #Current thread
c.s.s.SpringBootDemo3Application: #The class or interface name it belongs to (simplified)
Started SpringBootDemo3Application in 1.497 seconds (JVM running for 1.857)#Log information

For a single piece of log information, the date, trigger location, and recording information are the core information. The level is used for filtering, and the PID and thread name are used for precise analysis.

logging:
    pattern:
        console: "%d %clr(%p) --- [ t] %clr(%-40.40c){cyan} : %m %n"

4.3. Log files

Logs cannot only be displayed on the console, but must be recorded in files for later maintenance and review. There are various strategies for the use of log files, such as daily recording, classified recording, post-alarm recording, etc. Here we mainly study how log files are recorded. The format of recording logs to a file is very simple, just set the log file name.

logging:
    logback:
        rollingpolicy:
            max-file-size: 3KB
            file-name-pattern: server.%d{yyyy-MM-dd}.%i.log