springboot project practice - Chapter 02

Posted by raspberryh on Wed, 26 Jan 2022 07:52:14 +0100

1. Introduction to this chapter (omitted)

2. How to quickly generate a Springboot project (omitted)

3. git operation of local code associated with remote warehouse

git init->git add . -> git commit -m "remarks" - > git remote add origin your remote warehouse address - > git push -u origin master

4. New cognition of springboot project

springboot project is a parent-child project, which is embodied in maven

springboot project is an embedded container that automatically uses tomcat to start the project

5. Start log optimization

5.1 logback log style

For springboot version 2.2 or above, directly add a new file logback spring XML to the resource folder. As long as it is this name, springboot can automatically recognize it.

Contents of the document:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- Modify the path-->
    <property name="PATH" value="./log"></property>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{ss.SSS} %highlight(%-5level) %blue(%-30logger{30}:%-4line) %thread %green(%-18X{LOG_ID}) %msg%n</Pattern>
        </encoder>
    </appender>

    <appender name="TRACE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${PATH}/trace.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${PATH}/trace.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <layout>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %-50logger{50}:%-4line %green(%-18X{LOG_ID}) %msg%n</pattern>
        </layout>
    </appender>

    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${PATH}/error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${PATH}/error.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <layout>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %-50logger{50}:%-4line %green(%-18X{LOG_ID}) %msg%n</pattern>
        </layout>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <root level="ERROR">
        <appender-ref ref="ERROR_FILE" />
    </root>

    <root level="TRACE">
        <appender-ref ref="TRACE_FILE" />
    </root>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Interpretation of documents:

<Pattern>
In the output format,% d represents time,% highlight represents highlight,% - 5level represents from left to right, displaying 5 characters,% blue

%d{ss.SSS}: date format, indicating seconds: milliseconds. Similarly, HH: mm: SS SSS means hour: minute: Second: millisecond. If you don't want any time unit, just remove it.
%highlight(%-5level): print log level
%blue(%-30logger{30}:%-4line)
%Thread: thread
%green(%-18X{LOG_ID})
%msg: log information
%n: Wrap < / pattern >

5.2 add log of successful startup

LOG.info("start success!");
LOG.info("address:\ thttp://127.0.0.1:{}",env.getProperty("server.port"));
Use env Getproperty ("property name") gets application Properties.

5.3 start pattern modification

Under resource, add a new one named banner Txt file, here http://patorjk.com/software/taag/#p=display&h=2&v=1&f=Flower%20Power&t=XXXQ , enter text or English in the box on the right, select a favorite pattern style, and copy to banner Txt inside. Start the Springboot service again, and you can see the new startup pattern

6. Develop the http interface of helloworld

6.1 develop helloworld interface (omitted)

6.2 project stratification

Interface: generally placed in the controller layer

Notes:

@requestMapping("/test"), routing

@restController returns a string type.

@The Controller returns to the page (if the front and rear ends are not separated, this annotation is basically unnecessary). This annotation is not needed in this actual battle.

There is a class annotation @ ComponentScan("com.xxx.wiki") in the startup class. This annotation is used to increase the scanning return of the springboot project. For example, if we know where the startup class is, the contents in the subdirectory of the startup class will be scanned by default, but if the startup class is not in the default location or in the default location, However, we still want to scan some additional sub items that are not in the startup class, so we can expand the scanning scope with the annotation @ ComponentScan("com.xxx.wiki", "com.xxx.wiki")

7.idea has its own http client test interface

7.1 benefits: reduce the inefficiency caused by window switching; Solve the problem that the browser cannot access the post request

7.2 how to use it?

(1) Create a new one under the project file For files with HTTP suffix, the file name is optional, and the file suffix must be HTTP, such as test http

(2) In test Enter gtr in the http folder to generate a GET type http request without parameters.

GET http://localhost:80/api/item
Accept: application/json

###

The shortcut key is here in idea: idea attribute live_templates find httprequest and open it to see the default request template prepared by idea. Note that if test If multiple http requests are written in the http file, keep "####" to isolate multiple requests. Of course, we can also customize our own templates, but I won't do it at present

The generated HTTP request is a template. Change it into a request suitable for your project, and then launch the request (test.http file, there is a green triangle start key next to each request, and you can launch the request). The logs of all the initiated requests can be found in the project root directory, such as looking for In idea/httpRequests, there are multiple log files, and each file represents the log of a request.

8.Springboot configuration

8.1 default profile

1. It can automatically identify resource / application Properties file (this is the default), which can automatically identify resource / config / application Properties (this is self built). When these two files are both, the inner file takes effect.

It can also automatically identify {resource / application YML, or automatically identify resource / config / application yml.

2. It can automatically identify bootstrap Properties is generally used for dynamic configuration. Online modifications can be implemented and take effect in real time. It can generally be used with nacos.

3.yaml and Conversion of properties: https://toyaml.com/index.html .

4. Summary of 1 and 2:

springboot will automatically recognize the following group of files,

application.properties/yml file and config / application properties/yml 

springcloud will automatically recognize the following group of files,

bootstrap.properties/yml file and config / bootstrap properties/yml 

8.2 user defined configuration items

We are in application Redefine server in properties Port = 8088, overwriting the default value of 8080

We can also use application Configure another property: test config=test

Then, use this in the controller:

    @Value("${test.config}")// @value annotation, ${} package configuration name,
    private String testConfig;//Define this variable. Value is used for this variable. See how the @ value annotation is used
@GetMapping("/test/config")//Write an interface and return the read configuration value
    public String test(){
        return "test"+":"+testConfig;
    }

Write a test HTTP request (gtr), test it

GET http://localhost:8088/test/config
Accept: application/json

###

The results are as follows:

GET http://localhost:8088/test/config

HTTP/1.1 200 
Content-Type: application/json
Content-Length: 9
Date: Wed, 19 Jan 2022 05:09:43 GMT
Keep-Alive: timeout=60
Connection: keep-alive

test:test

Response code: 200; Time: 105ms; Content length: 9 bytes

OK! Test passed

In addition, the default configuration is written as @ Value("${test.config: default value}"). If the configuration value cannot be read in the configuration file, the default value will be read here.

9. Hot deployment (omitted)

 

Topics: Java