Many netizens will ask me from time to time, how to test the spring boot project, how to deploy it, and whether there are any good deployment solutions in production? This article will introduce how spring boot is developed, debugged, packaged and finally put into production and launch.
Development stage
Unit Testing
The most important thing during the development stage is unit testing. Springboot's support for unit testing has been perfected.
1. Add spring-boot-starter-test package reference to the pom package
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency>
2. Development and testing
Taking the simplest helloworld as an example, you need to add: @RunWith(SpringRunner.class) and @SpringBootTest annotations to the class head of the test class. Just add @Test at the top of the test method, and finally right-click on the method to run.
@RunWith(SpringRunner.class)@SpringBootTestpublic class ApplicationTests { @Test public void hello() { System.out.println("hello world"); }}In actual use, you can inject dao layer code or service layer code according to the normal use of the project for testing and verification. spring-boot-starter-test provides many basic usages, and what is even more rare is that it adds support for Controller layer testing.
//Simplely verify whether the result set is correct Assert.assertEquals(3, userMapper.getAll().size());//Verify the result set, prompt Assert.assertTrue("Error, the correct return value is 200", status == 200); Assert.assertFalse("Error, the correct return value is 200", status != 200);MockMvc is introduced to support testing of the Controller layer. The simple example is as follows:
public class HelloControlerTests { private MockMvc mvc; //Initialize execution @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build(); } //Verify whether the controller responds normally and prints the return result @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); } //Verify whether the controller responds normally and determines whether the return result is correct @Test public void testHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Hello").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Hello World")); }}Unit testing is the first barrier to verify your code. You should develop the habit of unit testing every time you write a part of your code. Don’t wait until all of them are integrated before testing. After integration, it is easy to miss the bugs at the bottom of the code because you pay more attention to the overall operation effect.
Integration Testing
After the overall development is completed, the integration test is entered. The startup entrance of the spring boot project is in the Application class. You can start the project by running the run method directly. However, during the debugging process, we must constantly debug the code. If you need to manually restart the service every time the code is modified, it will be very troublesome. Spring boot provides hot deployment support very considerately, which is very convenient for debugging and use in web projects.
Pom needs to add the following configuration:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency></dependencies><build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin></plugins></build>
After adding the above configuration, the project supports hot deployment, which is very convenient for integration testing.
Going production and going online
Actually, I think this stage should be relatively simple and generally divided into two types: one is to package it into a jar package and execute it directly, and the other is to package it into a war package and put it under the tomcat server.
Make it into a jar package
If you are using maven to manage your project, execute the following command
cd project and directory (same level as pom.xml) mvn clean package## or execute the following command## to exclude the test code and package mvn clean package -Dmaven.test.skip=true
After packaging is completed, the jar package will be generated in the target directory. The name is usually the project name + version number.jar
Start the jar package command
java -jar target/spring-boot-scheduler-1.0.0.jar
In this way, as long as the console is closed, the service will not be accessible. Let's start the following by running in the background:
nohup java -jar target/spring-boot-scheduler-1.0.0.jar &
You can also choose to read different configuration files when starting
java -jar app.jar --spring.profiles.active=dev
You can also set jvm parameters at startup
java -Xms10m -Xmx80m -jar app.jar &gradle
If you are using gradle, use the following command to package
gradle buildjava -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar
Make it into a war bag
The first type can be used to export the war package through the development tool eclipse, and the other type is to use commands to complete it. Here we mainly introduce the latter one.
1. Maven project, modify the pom package
Will
<packaging>jar</packaging>
Change to
<packaging>war</packaging>
2. Exclude tomcat when packaging.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope></dependency>
Here, set the scope property to provided so that the JAR package will not be included in the final WAR, because servers such as Tomcat or Jetty will provide relevant API classes at runtime.
3. Register the startup class
Create ServletInitializer.java, inherit SpringBootServletInitializer, override configure(), and register the startup class Application. When an external web application server builds a Web Application Context, the startup class will be added.
public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); }}Final execution
mvn clean package -Dmaven.test.skip=true
The project name + version number.war file will be generated in the target directory, and copy it to the tomcat server to start.
gradle
If you are using gradle, the basic step is the same. Add war support in build.gradle and exclude spring-boot-starter-tomcat:
...apply plugin: 'war'...dependencies { compile("org.springframework.boot:spring-boot-starter-web:1.4.2.RELEASE"){ exclude mymodule:"spring-boot-starter-tomcat" }}...Use the build command again
gradle build
war will be generated in the build/libs directory.
Production Operation and Maintenance
View the value of JVM parameters
You can follow the jinfo command that comes with java:
jinfo -flags pid
Let’s see what GC is used after the jar is started, how much memory is in batches in the new generation and the elderly. The examples are as follows:
-XX:CICompilerCount=3 -XX:InitialHeapSize=234881024 -XX:MaxHeapSize=3743416320 -XX:MaxNewSize=1247805440 -XX:MinHeapDeltaBytes=524288 -XX:NewSize=78118912 -XX:OldSize=156762112 -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseParallelGC-XX:CICompilerCount : Maximum parallel compiles -XX:InitialHeapSize and -XX:MaxHeapSize: Specify the initial and maximum heap memory size of the JVM -XX:MaxNewSize: Maximum allocable size for the new generation of memory in the JVM heap area... -XX:+UseParallelGC: Garbage collection uses Parallel collector
How to restart
Simple and crude
Directly kill the process and start the jar package again
ps -ef|grep java ##get the pidkill for Java program -9 pid## Restart Java again -jar xxxx.jar
Of course, this method is more traditional and violent, so it is recommended that you use the following method to manage it
Script execution
If you are using maven, you need to include the following configuration
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration></plugin>
If you use gradle, you need to include the following configuration
springBoot { execute = true}Startup method:
1. You can start directly in ./yourapp.jar
2. Register as a service
You can also make a soft link to point to your jar package and add it to init.d, and then start it with commands.
init.d Example:
ln -s /var/yourapp/yourapp.jar /etc/init.d/yourappchmod +x /etc/init.d/yourapp
This way you can use the stop or restart command to manage your application.
/etc/init.d/yourapp start|stop|restart
or
service yourapp start|stop|restart
At this point, the test, joint coordination and packaging of springboot projects have been introduced. You can find time to study the automated operation and maintenance of springboot and the combination of springboot and docker.
Sample code - github
Sample code-Code cloud
Summarize
The above is the method of spring boot test packaging and deployment introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!