SpringBoot operation and maintenance practical articles, packaging, operation, advanced configuration, multi-environment development, log


Practical articles on SpringBoot operation and maintenance

After the release of the basic chapter, I saw a lot of comments from friends on the Internet, and helped more than 100 friends solve some problems they encountered, and some problems have been found to be typical. It is expected that some problems will be in the right place in the next chapter Add it to this set of courses and provide it to everyone as a solution.


From now on, we will enter the study of the practical chapter. The practical chapter is based on the foundation of the basic chapter and complements the knowledge map of SpringBoot. For example, in the basic chapter, only the grammatical format of yaml is explained, but there are still many pitfalls in the practical development process when writing yaml files, which must be learned in the practical chapter.


The practical chapter is divided into two parts, namely the operation and maintenance practical chapter and the development practical chapter. In fact, the standard of division is formulated by myself, because some of the knowledge in it is still relatively scattered. The purpose of dividing into two stages is to better classify similar knowledge points and help learners find the relationship between knowledge. This is helpful for the memory storage and conversion of knowledge. After a series of repeated knowledge and strengthening exercises, the temporary memory will be converted into a permanent memory. When making a course, the goal should not only be to finish the lecture, but also to aim at the learning gains of the learners. This is also the basic philosophy I have been adhering to in teaching for so many years.


Let's start with the practical operation and maintenance chapter. In the practical operation and maintenance chapter, I position the learners to play with the configuration and prepare for the integration of various technologies in the practical development chapter. Compared with the practical development chapter, the content of the practical operation and maintenance chapter is slightly thinner, and some knowledge modules are covered in both the practical operation and maintenance chapter and the practical development chapter, and these contents are placed in the practical development chapter. Let’s not talk nonsense, let’s take a look at what is included in the operation and maintenance practical article:
1. Packaging and running of SpringBoot programs
2. Advanced configuration
3. Multi-environment development
4. Logs


Let's start the first part of the learning of SpringBoot program packaging and operation


YW-1. Packaging and running of SpringBoot program

Friends who have just started to develop and learn may have a wrong understanding of a knowledge. We write programs every day under Idea, and run them under Idea.

image-20211201091317258

But after the actual development is completed, it is impossible for our project to run on our own computer.

image-20211201091341645

The programs we will make in the future will run on a dedicated server. Simply put, it is to put the program you make on a computer that runs independently. This computer is more professional than the computer you develop and use, and it has a security level in all aspects. Much more than your current computer.

image-20211201091502040

Then how to place our program on this dedicated computer, we need to organize our program into a file first, and then transfer this file to this server. There are two processes here, one is the packaging process, and the other is the running process.


Kind tips

In order to ensure the adaptability of the environment, the enterprise project will adopt the following process to release the project, and this process will not be discussed here.
1. The development department uses Git, SVN and other version control tools to upload the project to the version server.
2. The server uses the version control tool to download the project.
3. The server uses the Maven tool to rebuild the project in the current real machine environment
. 4. Start the service


Continue to talk about our packaging and running process. The so-called packaging refers to converting the program into an executable file, and the so-called running refers to the file generated by the packaging without relying on the development environment. The above two operations have corresponding commands that can be executed quickly.


Program packaging

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 similar to the project name will be generated, and its name is composed of module name + version number + .jar.


Program running

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

java -jar 工程包名.jar

After executing the program packaging instruction, the program runs normally, which is no different from executing the program under Idea.


Special attention : If the jdk environment of java is not installed in your computer, the above operations cannot be performed 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 section of configuration must not be deleted, otherwise the program cannot be executed normally after packaging.

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

Summarize

1. The SpringBoot project can run the jar file independently based on the java environment to start the service.
2. The SpringBoot project executes the mvn command package for packaging.
3. Execute the jar command: java –jar project name.jar


Processing of SpringBoot program packaging failure

Some small partners will have some problems after packaging and executing, which will cause the program to fail to execute normally, such as the following phenomenon

image-20211201094223991

If you want to understand this problem, you need to talk about the working mechanism of the .jar file. If you know this, you will know how to avoid such problems.


Engaging in java development usually comes into contact with a lot of jar packages, such as the driver jar package of mysql, and what we get after packaging the program above is also a jar file. At this time, if you use the above java -jar command to execute the mysql driver jar package, the above non-executable phenomenon will appear, but why can our SpringBoot project be executed? In fact, it is because the packaging method is different.


In the pom.xml of the SpringBoot project, there is the following set of configurations. This set of configurations determines whether the packaged package can be executed.

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

We enable this configuration and comment out this configuration to perform two packages respectively, and then observe the difference between the two packaged packages. There are 3 obvious features 1. The size of the packaged file is different. 2. The size of the
packaged
package The content contained is different
3. The content of individual files in the packaging program is different


Look at the first phenomenon, the file size is different. The package size generated by packaging with configuration is as follows:

image-20211201095610270

It is not difficult to see that the volume of the package with configuration is 30 times larger than that without configuration, so what is in it? Can it be so different? Let's see what's different inside.

image-20211201101541267


image-20211201101652868

We found that the content is completely different, only one directory is the same, called META-INF. Open the classes directory under the BOOT-INF directory in the large-capacity program package, and we find that the contents are exactly the same as those in the small-capacity program package.

image-20211201101805569


image-20211201101652868


It turns out that the large program package contains other things besides the contents of the small program package. What are there? Go back to the BOOT-INF directory and open the lib directory, which shows a lot of jar files.

image-20211201102025791

It is not difficult to find that these jar files are the files corresponding to the coordinates imported when we made this project. You can probably figure it out. In order to make the program that is packaged and generated by itself run independently, the SpringBoot program not only packages the content developed by itself in the project, but also packages all the jar packages that need to be used for the current project operation. Why do you do this? Just to be able to run independently. The current program can run independently without relying on any resources outside the package. This is also the main reason why the capacity of the large package is 30 times that of the small package.


Let’s see what’s different about the large program package. The outermost directory contains an org directory. Enter this directory. The directory name is org\springframework\boot\loader. You can find a JarLauncher.class file in it. First , Remember this file. Looking at this set of directory names again, it is obviously a Spring directory name. Why should the Spring framework be packaged into this package? Not sure.


Go back to the outermost directories of the two packages, and check that there is a file called MANIFEST.MF under the folder META-INF with the same name, but the size is different. Open the file and compare the content difference


MANIFEST.MF for small files

Manifest-Version: 1.0
Implementation-Title: springboot_08_ssmp
Implementation-Version: 0.0.1-SNAPSHOT
Build-Jdk-Spec: 1.8
Created-By: Maven Jar Plugin 3.2.0

MANIFEST.MF for bulk files

Manifest-Version: 1.0
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Implementation-Title: springboot_08_ssmp
Implementation-Version: 0.0.1-SNAPSHOT
Spring-Boot-Layers-Index: BOOT-INF/layers.idx
Start-Class: com.itheima.SSMPApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Build-Jdk-Spec: 1.8
Spring-Boot-Version: 2.5.4
Created-By: Maven Jar Plugin 3.2.0
Main-Class: org.springframework.boot.loader.JarLauncher

There are obviously a few more lines of information in the large file than in the small file, and the last line of information is Main-Class: org.springframework.boot.loader.JarLauncher . What does this sentence mean? If you use java -jar to execute this package, the class configured by the Main-Class attribute will be executed, which happens to be the file you saw earlier. It turns out that the Spring framework in the SpringBoot packager is here to serve. And this org.springframework.boot.loader.JarLauncher class internally searches for the class configured in the Start-Class attribute and executes the corresponding class . This property also exists in the current configuration, corresponding to our bootstrap class name.


Now the function of this group of settings is clear.
1. After the SpringBoot program adds configuration, a special package will be created, including some functions of the Spring framework, the original project content, and the jar package that the original project depends on.
2. First read the MANIFEST.MF file The Main-Class attribute in is used to mark the class to run after executing the java -jar command.
3. When the JarLauncher class is executed, it will find the Start-Class attribute, which is the name of the startup class.
4. When running the startup class, it will run the content of the current project
5. When running the current project, the dependent jar package will be used and searched from the lib directory


It seems that in order to run independently, the SpringBoot package has taken great pains to add all the resources that need to be used to this package. This is why this jar package can run independently.


Look at the previous error message:

image-20211201094223991

Since that configuration was not used during packaging, a common jar package was formed after packaging, and there is no attribute corresponding to Main-Class in the MANIFEST.MF file, so the runtime prompts that the main list attribute cannot be found. That's the reason for the error.


It is not very meaningful for our programming to understand the above content, but it is helpful for you to understand the mechanism of the independent operation of the SpringBoot project. In fact, the overall process is mainly to lead everyone to analyze. If you encounter similar problems in the future, ask yourself more questions and why, and maybe you can solve the problem independently.


Summarize

The spring-boot-maven-plugin plugin is used to package the current program into a package that can run independently


Command line startup common problems and solutions

When you start the SpringBoot project in the DOS environment, you may encounter the problem of port occupation. Give everyone a set of commands, no need to study in depth, just make a backup.

# 查询端口
netstat -ano
# 查询指定端口
netstat -ano |findstr "端口号"
# 根据进程PID查询进程名称
tasklist |findstr "进程PID号"
# 根据PID杀死任务
taskkill /F /PID "进程PID号"
# 根据进程名称杀死任务
taskkill -f -t -im "进程名称"

There are actually a series of configurations and parameters about packaging and running the program. Let’s talk about it in the following content. Let’s start here and know how to package and run the program.


SpringBoot project quick start (Linux version)

In fact, there is not much difference between the program running under the Linux system and the program running under the Windows system. The commands are still the same set of commands, but you may not be familiar with Linux commands, which will lead to various problems. For example, how to close the firewall, how to query the IP address, how to install the JDK, and so on. This is not the key content for everyone to popularize, just understand the overall process.


YW-2. Advanced configuration

Part of the configuration has been discussed in the basic chapter. Generally speaking, the configuration of the basic chapter is to let everyone master the format of the configuration. For example, how to write configuration files and how to read written data are all basic grammar-level knowledge. In the practical chapter, we will focus on the application of configuration. Next, we will start to learn the first part of advanced configuration related content. Why do we say the first part, because there is corresponding advanced configuration knowledge to be learned in the practical development chapter.


YW-2-1. Temporary attribute setting

Our package is now packaged and ready for release. But after the program package is completed, the configuration inside is already fixed, for example, the server port is configured to be 8080. If I want to start the project and find that an application has already been started on my server and occupies port 8080, it will be embarrassing at this time. Is it necessary to modify the packaged program again? For example, I want to change the packaged program startup port to 80.

image-20211206095113771


image-20211206095524343


image-20211206095101581


SpringBoot provides flexible configuration methods. If you find that individual properties in your project need to be reconfigured, you can use temporary properties to quickly modify some configurations. The method is also very simple, just add the corresponding parameters at startup.

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

The above command is the command to start the SpringBoot package. After the command is entered, enter a space, and then enter two - signs. Next, add the corresponding parameters in the form of attribute name = attribute value. Remember, the format here is not the writing format in yaml. When there are multi-level names for attributes, dots are used to separate them, which is exactly the same as the attribute format in the properties file.


If you find that there is more than one attribute to be modified, you can continue to write according to the above format, and use spaces to separate attributes.

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

property loading priority

Now our program configuration is controlled by two places, the first configuration file and the second temporary attribute. And we found that the loading priority of temporary attributes is higher than that of configuration files. Is there any other way to configure it? In fact, there are, and there are quite a few. Open the corresponding content in the official document, and you can view the priority order of configuration reading. Here is the address: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

image-20211206100859236
We can see that there are actually 14 configuration positions, and we are using 2 of them now. Article 3 Config data refers to the use of configuration files, and Article 11 Command line arguments refers to the use of temporary command line parameters. The order of these 14 configurations is the order in which SpringBoot loads the configuration. The implication is that the temporary properties of the command line have a higher priority than the loading of the configuration file, so the priority on the top of this list is low, and the priority on the bottom is high. In fact, this thing does not need to be memorized, you just remember one thing, you know what effect you want in the end, no matter how high or low the order is, you must configure it in the order you want when developing. This order is just to help you analyze when you can't figure out the problem.


For example, you now load a user.name attribute. As a result, you find that the result is different from what you thought. It must be that other attributes with a higher priority than yours have overwritten your configuration attributes. Then you can look at the order and check one by one. Which location has the potential to override your attributes.


I asked this question when I saw my friends learning the basics in the course comment area, and it was for this reason. The user.name attribute value is configured in yaml, and when it is read out, it is not its own configuration value, because there is an attribute called user.name in the system attribute, and the two conflict with each other. The loading priority of system properties is No. 5 in the above list, which is higher than No. 3, so SpringBoot will eventually load the system configuration property user.name.


Summarize

1. When using the jar command to start the SpringBoot project, you can use temporary properties to replace the properties in the configuration file
2. Add temporary properties: java –jar project name.jar –- property name=value
3. Multiple temporary properties are separated by spaces
4. The temporary attribute must be an attribute supported by the current boot project, otherwise the setting is invalid


Use temporary properties in the development environment

Temporary use is currently available, but the temporary attributes entered through the command line must be correct when going online. Then we must test the configuration values ​​of these attributes in the development environment. Let's talk about how to use temporary attributes in the development environment, which is actually how to operate in the Idea interface.


Open the running interface of the SpringBoot boot class and find the configuration items in it. Among them, the position corresponding to Program arguments is to add temporary attributes, and you can add a few to try the effect.

image-20211206101947622

Doing this can actually generate a thought. Those who are familiar with java programming should know that when we run the main method, if we want to use the parameters of the main method, that is, the args parameter below, it is added at the above position parameter.

public static void main(String[] args) {
     
     
}

It turns out that this is the case, and the parameters can be obtained through this args. Let's look at how our boot class is written

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

This args parameter is actually passed to the run method. It seems that the temporary parameters configured in Idea are passed to our program through this location. The implication is that if this args is not used here, will the entrance to the external transfer of temporary attributes be disconnected? This is the case, we can use the following calling method, so that external temporary properties cannot enter the SpringBoot program.

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

Or you can use the following format to play this operation, that is, the configuration is not written in the configuration file, but directly written as a string array and passed to the program entry. Of course, this approach has no practical development significance.

public static void main(String[] args) {
     
     
    String[] arg = new String[1];
    arg[0] = "--server.port=8082";
    SpringApplication.run(SSMPApplication.class, arg);
}

Summarize

When starting the SpringBoot program, you can choose whether to use the command line attribute to pass the startup properties for the SpringBoot program


think

It is now possible to temporarily change the configuration before starting the project using temporary properties, but new problems have arisen again. Temporary attributes are easy to use because they are easy to use, but writing too much will be troublesome. For example, I now have a need to configure 20 values ​​​​with temporary attributes when going online. This is troublesome. Can you make it simpler and manage it centrally? For example, make a file and load the specified file? It's really good. How to do it? Let's talk about it in the next section.


YW-2-2. Classification of configuration files

SpringBoot provides configuration files and temporary properties to configure the program. I have been talking about temporary attributes before, and this section will talk about configuration files. In fact, we have been using this configuration file, but we use one of the four levels of configuration files provided by SpringBoot. The four levels are:
1. The configuration file under the class path (this is what I have been using, that is, the application.yml file in the resources directory)
2. The configuration file under the config directory under the class path
3. The configuration file in the directory where the package is located
4. The configuration file under 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 4 kinds of files are provided for you to write the 4 kinds of configuration files. The functions are the same, and they are all for configuration. Then what everyone cares about is the difference. Yes, it is because of the different positions that there are differences. Generally speaking, if all four configuration files exist, there is a question of priority. To put it bluntly, I have all four files, and all of them have the same configuration, and the question of who takes effect. The loading priority order of the above 4 files is

1. file :config/application.yml 【最高】
2. file :application.yml
3. classpath:config/application.ym
4. classpath:application.yml 【最低】


So why design such a variety? Talk about one of the most typical applications.
1. Scenario A: As a developer, when you make a program, in order to facilitate your own code writing, the configured database must be connected to your own machine. We use the level 4, which is the application.yml that has been used before.
2. Scenario B: Now that the project development has reached a stage, joint debugging and testing are required. The connected database is the database of the test server, and a set of configurations must be changed. You can choose to change all the content in your previous file, and it is not troublesome at present.
3. Scenario C: After the test, everything is OK. You continue to write your code, and you find that the configuration file you originally wrote has been changed to the content of the test server, and you have to change it back. Do you understand now? In scene B, all your content has been changed, you need to change it back now, what about in the future? Do you want to change it?


The solution is very simple. You can quickly solve this problem by using the above 3-level configuration file, and just write another configuration. Two configuration files coexist, because the configuration loading priority in the config directory is higher than yours, so if the configuration item is the same as the content in level 4, it will be overwritten. Is this very simple?


When are levels 1 and 2 used? This level will be used after the program is packaged, regardless of what is written in the configuration of your program? My level is high and I can easily cover you, so I don't have to consider these configuration conflicts.


Summarize

1. Configuration files are divided into 4 types 1.1. Project class path configuration file : for developers to
develop and test locally Configure the confidential online environment for operation and maintenance personnel 1.4. Configuration files in the project path config directory: serve the overall control of the operation and maintenance manager 2. The attributes between multi-level configuration files are applied to the program in the form of superposition and coverage




YW-2-3. Custom configuration files

The configuration file we used for configuration before is application.yml. In fact, the name of this file can also be changed, which is convenient for maintenance. For example, I held an event on April 1, 2020, and left a set of configurations. The event was canceled on May 1, 2020, and the original configuration was restored. At this time, I only need to change the configuration file again. But you can't modify the original configuration file, otherwise, after the activity is completed, the configuration of the activity will not be retained, which is not conducive to maintenance.


There are two ways to customize the configuration file as follows:
Method 1: Use temporary attributes to set the configuration file name. Note that it is only the name without the extension

image-20211206105548238


Method 2: Use temporary attributes to set the configuration file path, which is the full path name

image-20211206105716450


You can also set to load multiple configuration files
image-20211206105750285

One of the properties used is spring.config.name, and the other is spring.config.location, which must be clearly distinguished.


Kind tips

We are now studying SpringBoot single project, which is the single server version. In fact, enterprise development now uses more multi-server projects based on SpringCloud technology. This configuration method is completely different from what we are learning now. All servers will no longer set their own configuration files, but will obtain configuration through the configuration center and dynamically load configuration information. Why did you do this? centralized management. I won't talk about these here anymore, and I will talk about these things later.


Summarize

1. The name of the configuration file can be modified by setting the startup parameters
2. The path of the configuration file can be modified by setting the startup parameters
3. The configuration file can be set through the configuration center during microservice development


YW-3. Multi-environment development

The content of the talk is getting closer and closer to online development. Let's talk about multi-environment development.


What are multiple environments? In fact, it means that the program written on your computer will eventually be put on someone else's server to run. Every computer environment is different, this is multi-environment. Common multi-environment development mainly takes into account three kinds of environment settings, the development environment - used by oneself, the test environment - used by the company, and the production environment - used by Party A's father. Because these are absolutely different three computers, the environment must be different, such as the connected database, the set access port and so on.

insert image description here


YW-3-1. Multi-environment development (yaml single file version)

So what is multi-environment development? Just set different configuration properties for different environments. For example, when you develop by yourself, configure your port as follows:

server:
  port: 80

How would you like to design two sets of environments? separated by three minus signs

server:
  port: 80
---
server:
  port: 81

How to distinguish the two environments? name it

spring:
	profiles: pro
server:
	port: 80
---
spring:
	profiles: dev
server:
	port: 81

Which one should I use? Set which one to start by default

spring:
	profiles:
		active: pro		# 启动pro
---
spring:
	profiles: pro
server:
	port: 80
---
spring:
	profiles: dev
server:
	port: 81

It's that simple, it's OK to add another set of environments

spring:
	profiles:
		active: pro		# 启动pro
---
spring:
	profiles: pro
server:
	port: 80
---
spring:
	profiles: dev
server:
	port: 81
---
spring:
	profiles: test
server:
	port: 82

Among them, the above format of the environment name definition is an outdated format, and the standard format is as follows

spring:
	config:
    	activate:
        	on-profile: pro

Summarize

1. Multi-environment development needs to set up several common environments, such as development, production, and test environments.
2. Set up multi-environment use in yaml format—distinguish the boundaries of environment settings.
3. The difference between each environment lies in the configuration properties loaded
. 4. Enable certain This environment needs to be specified to be used at startup


YW-3-2. Multi-environment development (yaml multi-file version)

main configuration file

spring:
	profiles:
		active: pro		# 启动pro

Environment configuration file

server:
	port: 80

Because each of the environment configuration files 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 the file name to distinguish.


application-pro.yaml

server:
	port: 80

application-dev.yaml

server:
	port: 81

The file naming rules are: application-environment name.yml.


In the configuration file, if some configuration items are the same in all environments, these items can be written into the main configuration, and only those items that are different are written into the environment configuration file.
1. Set the public configuration in the main configuration file (global)
2. It is often used to set conflict attributes in the environment classification configuration file (local)


Summarize

1. Independent configuration files can be used to define environment properties
2. Independent configuration files are convenient for online system maintenance and updates and ensure system security


YW-3-3. Multi-environment development (properties multi-file version)

The earliest configuration file format provided by SpringBoot is in the properties format. Let’s also understand the multi-environment configuration in this format.


main configuration file

spring.profiles.active=pro

Environment configuration file
application-pro.properties

server.port=80

application-dev.properties

server.port=81

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


Summarize

properties file multi-environment configuration only supports multi-file format


YW-3-4. Multi-environment development independent configuration file writing skills

As a programmer, when you are engaged in configuration, you are often in a situation where the long-term must be combined and the long-term must be divided. Write it together at first, and then split it for the convenience of maintenance. The same is true for multi-environment development. Let me tell you how to do configuration independent management based on multi-environment development. Be sure to master it.


Preparation

Split all the configuration information in the configuration file according to the function and make it into an independent configuration file. The naming rules are as follows
1. application-devDB.yml
2. application-devRedis.yml
3. application-devMVC.yml


use

When using the include attribute to activate the specified environment, load multiple environments at the same time to make them take effect, and use commas to separate multiple environments

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

For comparison, now it is equivalent to loading the corresponding 3 sets of configurations when loading the dev configuration. The structure is very clear, what is used, and what is the corresponding name


Notice

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


improvement

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. Starting from version 2.4, SpringBoot uses the group attribute instead of the include attribute, which reduces the amount of configuration writing. To put it simply, I will write it first, and use whichever you like.

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

Looking at it now, if you switch from dev to pro, you only need to change it, is it over? Perfect!


Summarize

Multi-environment development uses the group attribute to set configuration file grouping, which is convenient for online maintenance and management


YW-3-5. Multi-environment development control

Multi-environment development is basically finished here, and finally a conflict issue. It is what to do if maven and SpringBoot set up multiple environments at the same time.


To deal with this conflict problem, you must first sort out a relationship, who is in the dominant position in multi-environment development. That is to say, if multiple environments are set up now, which one should be kept, and the other should follow the same setting.


What does maven do? What does SpringBoot do for project construction management and final generation of code packages? Simplified development. Simplification is not its leading role. In the end, it is 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:
1. First set up a specific environment in the maven environment
2. Just read the environment set by maven in SpringBoot


Set up multiple environments in maven (using attributes to distinguish environments)

<profiles>
    <profile>
        <id>env_dev</id>
        <properties>
            <profile.active>dev</profile.active>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>		<!--默认启动环境-->
        </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@

The above @property name@ is the grammatical format for reading the property value configured in maven.


Summarize

1. When Maven and SpringBoot control multiple environments at the same time, Mavn is the main one, and SpringBoot uses the @…@ placeholder to read the corresponding configuration property value of Maven. 2. On the premise of reading Maven configuration properties based on SpringBoot, if
in When testing the project under Idea, each update of pom.xml needs to be manually compiled to take effect


YW-4. Log

In the last part of the operation and maintenance article, let’s talk about logs. Everyone is familiar with logs, so let’s briefly introduce them. The log is actually to record the daily operation information of the program, and its main functions are as follows:
1. Debug code during programming period
2. Record information during operation period
3. Record important information about daily operation (peak traffic, average response time...)
4. Record application error information ( Error stack)
5. Record operation and maintenance process data (expansion, downtime, alarm...)


Maybe you guys are not used to using logs, it doesn't matter, just use it more slowly, just get used to it. If you want to enter a big factory, this is the most basic. Don't say that you have never used it when you go to the interview, it is over, and you have no chance.


YW-4-1. Use the log tool to record logs in the code

The usage format of the log is very fixed, so go directly to the operation steps:


Step ①

Add logging action

@RestController
@RequestMapping("/books")
public class BookController extends BaseClass{
     
     
    private static final Logger log = LoggerFactory.getLogger(BookController.class);
    @GetMapping
    public String getById(){
     
     
        log.debug("debug...");
        log.info("info...");
        log.warn("warn...");
        log.error("error...");
        return "springboot is running...2";
    }
}

The log object in the above code is the object used to record the log, and the operations of log.debug and log.info below are the API for writing the log.


Step ②

Set log output level


After the log is set up, you can choose which participating records according to the settings. Here it is set according to the level of the log. There are 6 levels of logs, which are:
1. TRACE: running stack information, low usage rate
2. DEBUG: programmer debugging code usage
3. INFO: recording operation and maintenance process data
4. WARN: recording operation and maintenance process alarm data
5. ERROR: Record error stack information
6. FATAL: Disaster information, merged into ERROR


Under normal circumstances, use DEBUG during development, use INFO after going online, and use WARN for operation and maintenance information records. Here's how to set the log level:

# 开启debug模式,输出调试信息,常用于检查系统运行状况
debug: true

Such a setting is too simple and rude, and the log system usually provides fine-grained control

# 开启debug模式,输出调试信息,常用于检查系统运行状况
debug: true

# 设置日志级别,root表示根节点,即整体应用日志级别
logging:
	level:
    	root: debug

You can also set more fine-grained control


Step ③

Set the log group to control the log output level corresponding to the specified package, or directly control the log output level corresponding to the specified package

logging:
	# 设置日志组
    group:
    	# 自定义组名,设置当前组中所包含的包
        ebank: com.itheima.controller
    level:
    	root: warn
        # 为对应组设置日志级别
        ebank: debug
    	# 为对包设置日志级别
        com.itheima.controller: debug

To put it bluntly, it is to set the overall settings and each package. If you feel that the settings are troublesome, first divide the packages into groups and set them for the groups. Nothing, that's all.


Summarize

1. The log is used to record development, debugging and operation and maintenance process messages.
2. There are 6 types of log levels, usually 4 types are sufficient, namely DEBUG, INFO, WARN, ERROR
3. It can be performed in the form of log groups or code packages Log display level control


teach you a trick

Optimize log object creation code


When writing code, each class must write and create logging objects. This can be optimized by using the tool classes provided to us by the lombok technology used earlier.

@RestController
@RequestMapping("/books")
public class BookController extends BaseClass{
     
     
    private static final Logger log = LoggerFactory.getLogger(BookController.class);	//这一句可以不写了
}

After importing lombok, use annotations to get it done, and the log object name is log

@Slf4j		//这个注解替代了下面那一行
@RestController
@RequestMapping("/books")
public class BookController extends BaseClass{
     
     
    private static final Logger log = LoggerFactory.getLogger(BookController.class);	//这一句可以不写了
}

Summarize

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


YW-4-2. Log output format control

The log 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 record format of the current log.

image-20211206123431222

For a single log message, the date, trigger location, and record information are the core information. The level is used for filtering, and the PID and thread name are used for precise analysis. After knowing this information, you can DIY the log format. This course does not do detailed research, interested friends can learn related knowledge. The writing format of the official log template simulated in the course is given below for everyone to learn.

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

Summarize

Log output formatting rules


YW-4-3. Log files

The log information shows that the records have been controlled, so let's talk about the dumping of the logs. The log cannot only be displayed on the console, but should be recorded in a file for later maintenance and reference.


There are various strategies for the use of log files, such as daily records, classified records, post-alarm records, etc. Here we mainly study how log files are recorded.


The format of logging to a file is very simple, just set the log file name.

logging:
	file:
    	name: server.log

Although the above format can be used to record the log, but in the face of complex online situations, a file record is definitely not able to meet the requirements of operation and maintenance. Usually, log files are recorded every day. At the same time, in order to facilitate maintenance, each The size of the log file. The common configuration methods for log files are given below:

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

The above format is based on the logback log technology to set the daily log file setting format. It is required to dump the information to the second file after the capacity reaches 3KB. %d in the file naming rules identifies the date, and %i is an incremental variable used to distinguish log files.


Summarize

1. Log records to files
2. Log file format settings


Operation and maintenance practical articles end

The practical operation and maintenance article will come to an end here, why not say it is over? Because there is still some knowledge in the operation and maintenance chapter, but the explanation is too scattered now. Therefore, it is also the embodiment of the teaching design of this course to combine these knowledge with the knowledge of the practical development.


In the overall operation and maintenance practical chapter, I took everyone to learn 4 pieces of content. First, I learned how to run the SpringBoot program, that is, the packaging and operation of the program. Next, I upgraded the configuration and learned it, no longer limited to the settings in the configuration file. , through temporary properties and external configuration files to control the configuration of the project. In the multi-environment development, I introduced a variety of multi-environment development formats. In fact, you can master one. In addition, I also told you some skills in multi-environment development and conflict resolution with maven. Finally, I introduced the log system to you. To be honest, the log is quite sloppy here, because most of the log-related knowledge should not be learned in this course. Here is just to tell you how to integrate and use it practically.


After reading the comments of all the friends, I know that you will continue to urge updates, and I am also working hard, let's work hard together, and see you in the practical development chapter. The practical development chapter will increase the frequency of updates. I will update it for everyone if I don’t finish it all. I will open up a part of it first, and then I will update it after I finish it. Um, well, let’s stop here.

Guess you like

Origin blog.csdn.net/weixin_51157081/article/details/132550373