The most basic knowledge points of microservice architecture spring boot

1. Create a SpringBoot project

concept

Spring Boot is a new framework provided by the Pivotal team, designed to simplify the initial setup and development of new Spring applications. The framework uses a specific way to configure, so that developers no longer need to define boilerplate configuration. In this way, Spring Boot aims to be a leader in the burgeoning field of rapid application development.

Spring Boot Features

  1. Create a standalone Spring application
  2. Embedded Tomcat without deploying WAR files
  3. Simplified Maven configuration
  4. Automatically configure Spring
  5. Provides production-ready features such as metrics, health checks and external configuration
  6. Absolutely no code generation and no configuration required for XML

Build the Spring Boot project

(1) Create a project, select Spring starter Project (you need to install Spring Tool Suite in Eclipse first), and press Next: 
write picture description here

(2) Fill in various information related to the project, and then Next: 
write picture description here

(3) Select the required Dependency, then Next: 
write picture description here 
(4) Finally, "Finish" starts to download the jar package, which takes a long time.

run the project

Project structure introduction

write picture description here

As shown in the figure above, the Spring Boot infrastructure consists of three files:

  1. src/main/java program development and main program entry
  2. src/main/resources configuration file
  3. src/test/java test program

Also, the directory suggested by spingboot results in the following: 
root package structure: com.example.myproject

com
  +- example
    +- myproject
      +- Application.java
      |
      +- domain
      |  +- Customer.java
      |  +- CustomerRepository.java
      |
      +- service
      |  +- CustomerService.java
      |
      +- controller
      |  +- CustomerController.java
      |

 

1. Application.java is recommended to be placed under the root directory, which is mainly used for some framework configurations 
. 2. The domain directory is mainly used for the entity and data access layer (Repository) 
3. The service layer is mainly business code 
4. The controller is responsible for page access control

pom.xml

There are two modules by default in the pom.xml file:

spring-boot-starter : core module, including auto-configuration support, logging and YAML;

spring-boot-starter-test : Test modules, including JUnit, Hamcrest, Mockito.

start a single controller

1. Create a controller

package com.ailianshuo.helloword.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello World";
    }
}

 

@RestController means that the methods in the controller are output in json format, no need to write any jackjson configuration

2. Start the controller to prepare 
to start a single controller according to the above code. You need to add the following code: 
(1) @EnableAutoConfiguration: The function is to let Spring Boot automatically configure the Spring framework according to the dependencies declared by the application, which reduces the the workload of developers. (You can also use @SpringBootApplication which is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with default properties) 
(2) Start the program: 
public static void main(String[] args) throws Exception { 
SpringApplication.run(**.class, args); 
}  The
complete code is as follows:

@EnableAutoConfiguration
@RestController
public class HelloWorldController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello World";
    }

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

 

3. Start a single controller 
(1) Right-click the main method in HelloWorldController, Run As -> Spring Boot App, and the project can be started.

write picture description here

(2) The compiler displays the following content, that is, the startup is successful. 
2017-08-19 11:12:49.814 INFO 4164 — [main] sbcetTomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 
2017-08-19 11:12:49.819 INFO 4164 — [main] cahcontroller.HelloWorldController : Started HelloWorldController in 3.351 seconds (JVM running for 4.573)

(3) Visit http://localhost:8080/hello in the browser to  see the effect.

Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot


Second, the rapid construction of RESTfull API simple projects

Edit pom.xml

[html] view plain copy

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.   
  6.     <groupId>com.lyw</groupId>  
  7.     <artifactId>springboot02</artifactId>  
  8.     <version>0.0.1-SNAPSHOT</version>  
  9.     <packaging>jar</packaging>  
  10.   
  11.     <name>springboot02</name>  
  12.   
  13.     <parent>  
  14.         <groupId>org.springframework.boot</groupId>  
  15.         <artifactId>spring-boot-starter-parent</artifactId>  
  16.         <version>1.4.0.RELEASE</version>  
  17.         <relativePath/> <!-- lookup parent from repository -->  
  18.     </parent>  
  19.   
  20.     <properties>  
  21.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  22.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  23.         <java.version>1.8</java.version>  
  24.     </properties>  
  25.   
  26.     <dependencies>  
  27.         <dependency>  
  28.             <groupId>org.springframework.boot</groupId>  
  29.             <artifactId>spring-boot-starter-web</artifactId>  
  30.         </dependency>  
  31.   
  32.         <dependency>  
  33.             <groupId>org.springframework.boot</groupId>  
  34.             <artifactId>spring-boot-starter-test</artifactId>  
  35.             <scope>test</scope>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.springframework.boot</groupId>  
  39.             <artifactId>spring-boot-devtools</artifactId>  
  40.         </dependency>  
  41.     </dependencies>  
  42.   
  43.     <build>  
  44.         <plugins>  
  45.             <plugin>  
  46.                 <groupId>org.springframework.boot</groupId>  
  47.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  48.             </plugin>  
  49.         </plugins>  
  50.     </build>  
  51. </project>  

 

Briefly explain the above configuration 

First look at the dependencies of the Spring-boot-start-web package

It can be seen that this package is actually some log packages and the built-in Tomcat JSON package SpringMVC/Web package, which almost explains why it runs directly.

In fact, this can be understood as simply encapsulating Spring to make our configuration more convenient.

The introduction of spring-boot-devtools and the learning of its dependent packages

This package contains some of Spring's core packages. . .

spring-boot-maven-plugin finally added a SpringBoot Maven plugin

Start writing code. . .

Springboot2Application.java

[java] view plain copy

  1. package com.lyw;  
  2.   
  3. import org.springframework.boot.SpringApplication;  
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  5.   
  6. @SpringBootApplication  
  7. public class Springboot02Application {  
  8.   
  9.     public static void main(String[] args) {  
  10.         SpringApplication.run(Springboot02Application.class, args);  
  11.     }  
  12. }  

 

User.java

[java] view plain copy

  1. package com.lyw.bean;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  * Title: User Description: Entity class Company: blog.csdn.net/lu1005287365/ 
  7.  *  
  8.  * @author L lulu 
  9.  */  
  10. public class User {  
  11.     private Integer id;  
  12.     private String name;  
  13.     private Date date;  
  14.     private char sex;  
  15.   
  16.     public Integer getId() {  
  17.         return id;  
  18.     }  
  19.   
  20.     public void setId(Integer id) {  
  21.         this.id = id;  
  22.     }  
  23.   
  24.     public String getName() {  
  25.         return name;  
  26.     }  
  27.   
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.   
  32.     public Date getDate() {  
  33.         return date;  
  34.     }  
  35.   
  36.     public void setDate(Date date) {  
  37.         this.date = date;  
  38.     }  
  39.   
  40.     public char getSex() {  
  41.         return sex;  
  42.     }  
  43.   
  44.     public void setSex(char sex) {  
  45.         this.sex = sex;  
  46.     }  
  47.   
  48. }  



UserControoler.java

[java] view plain copy

  1. package com.lyw.controller;  
  2.   
  3. import java.util.Date;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import org.springframework.web.bind.annotation.PathVariable;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RestController;  
  10.   
  11. import com.lyw.bean.User;  
  12.   
  13. @RestController  
  14. @RequestMapping(value = "/user")  
  15. public class UserController {  
  16.   
  17.     @RequestMapping  
  18.     public String index() {  
  19.         return "Hello BeiJing";  
  20.     }  
  21.   
  22.     @RequestMapping(value = "/getMap")  
  23.     public Map<String, Object> getThisMap(String msg) {  
  24.         Map<String, Object> map = new HashMap<>();  
  25.         map.put("Name", "LYW");  
  26.         map.put("Sex", "Big Guys");  
  27.         map.put("Message", msg);  
  28.         return map;  
  29.     }  
  30.   
  31.     @RequestMapping(value = "/getUser/{name}/{sex}")  
  32.     public User getUser (athPathVariable String name, athPathVariable char sex)  
  33.         User user = new User();  
  34.         user.setId(12);  
  35.         user.setName(name);  
  36.         user.setDate(new Date());  
  37.         user.setSex(sex);  
  38.         return user;  
  39.     }  
  40.   
  41. }  

 

Run the project:

Run the main method directly or use the maven command: spring-boot:run


 

The above is the result of the operation. .

explain

@RestController annotation: Looking at the source code, it actually encapsulates another layer to combine the two annotations @Controller and @RsponseBody

In this way, you should also have a preliminary understanding of SpringBoot. . . and will be easy to use

 

3. Spring Boot implements multi-environment configuration

In actual projects, we generally place some configuration files, which distinguish the environment. The general environment includes dev, test, prep, and prod, which correspond to development, testing, pre-release, and production. So how to implement different environments and use different configuration files in the spring boot project.

Step 1: Define application.properties for different environments

image.png

application.properties stores some common configuration. 
And the most important configuration [email protected]
application-dev.properties corresponds to the development environment 
application-test.properties corresponds to the test environment 
application-prep.properties corresponds to the pre-production environment 
application-prod.properties corresponds to the production environment

Step 2: Define profile in pom 
image.png

Step 3: maven command package 
package -Dmaven.test.skip=true -Pdev

Then the configuration of application-dev.properties and application.properties will be entered into the package at this time.

Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot
 

Fourth, Spring Boot application monitoring

Getting Started: Actuator Plugin

The Actuator plugin is a service provided natively by SpringBoot, which can be used to output many endpoint information in the application by exposing endpoint routing  . Let's fight it!

  • Add dependencies to pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

 

After starting the Spring Boot application, you can get some state information of the application by simply entering the endpoint information in the browser.

Common endpoints are listed as follows, you can try them one by one in detail:

Of course, only the /health and  /infoendpoints can be used at this time, and the others cannot be accessed due to permission issues. If you want to access the specified endpoint, you can add relevant configuration items in the yml configuration. For example, /metricsthe endpoint needs to be configured:

endpoints:
  metrics:
    sensitive: false

At this point the browser accesses the /metrics endpoint to get information such as the following:

Of course, you can also open all endpoint permissions, just configure the following:

endpoints:
  sensitive: false

After all, the monitoring capabilities provided by the Actuator plug-in are limited, and the UI is relatively simple, so a more mature tool is needed.

Spring Boot Admin Monitoring System

SBA is a further evolution based on Actuator, which is a monitoring tool for UI beautification and encapsulation of Actuator interfaces. Let's experiment.

  • First, create a Spring Boot Admin Server project as a server

Add the following dependencies to pom.xml:

Then enable Spring Boot Admin by annotating the main class of the application

Start the program, and the browser opens to  localhost:8081 view the Spring Boot Admin main page:

Spring Boot Admin main page

At this time, the Application column is empty, waiting for the application to be monitored to join

  • Create a Spring Boot application to monitor

Add the following dependencies to pom.xml

Then add the following configuration to the yml configuration to register the application to the Admin server:

As soon as the Client application starts, the Admin service immediately pushes a message, telling you that AdminTest is online:

App launch push message

At this point, go to the Admin main interface and find that the Client application has indeed been registered:

Client application has been registered

  • View Details

Detail information

  • View Metrics

Metrics information

  • View Environment

Environment Information

  • View JMX

JMX information

  • View Threads

Threads information

  • View Trace and Details

Trace information

Click JOURNAL at the top, and you will see the event changes of the monitored application:

Application event change information

It can be clearly seen from the figure that the application   jumps from the state of REGISTRATION → UNKNOWN → UP .

This will try all the endpoint information provided by the Actuator plugin in SBA.

Here I recommend an architecture learning exchange group to everyone. Communication and learning group number: 575745314 It will share some videos recorded by senior architects: Spring, MyBatis, Netty source code analysis, high concurrency, high performance, distributed, principles of microservice architecture, JVM performance optimization, distributed architecture, etc. These become the necessary knowledge system for architects. You can also receive free learning resources, which are currently benefiting a lot
image description

Five, Spring Boot log management

By default, Spring Boot's logs are output to the console and do not write to any log files.

To let Spring Boot output log files, the easiest way is to configure the logging.path key value in the application.properties configuration file, as follows: (The log file is spring.log)

logging.path=/var/log

The second method is to configure the logging.file key value in the application.properties configuration file, as follows:

logging.file=/var/log/myapp.log

The two configuration methods are suitable for the development stage, but there are certain problems in the deployment. For example, when deploying to different environments, it may be necessary to modify the application.properties file, which means that it needs to be repackaged and deployed again, which is inconvenient.

In view of this, Spring Boot provides a way to override the key values ​​in the application.properties configuration file, by specifying parameters on the command line to achieve overriding - at runtime, the command line parameters are treated as standard system properties, as follows :

java -jar -Dlogging.path=/tmp myapp.jar

Later, you can also override this value when invoking Spring Boot's Maven plugin from the command line. However, using system properties directly is invalid for the plugin approach. You need to use the run.jvmArguments parameter to specify the system property and set the desired value:

mvn spring-boot:run -Drun.jvmArguments="-Dlogging.path=/tmp"

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326662039&siteId=291194637