Spring boot testing and deployment method, springboot

Source: Internet
Author: User

Spring boot testing and deployment method, springboot

Many netizens may ask me from time to time how to test the spring boot project, how to deploy the project, and whether there is any good Deployment Solution in production? This article introduces how to develop, debug, and package spring boot to the final production environment.

Development Phase

Unit Test

In the development phase, the most important thing is unit testing. springboot's support for unit testing has been improved.

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

Take the simplest helloworld as an example. In the Class header of the test class, add @ RunWith (SpringRunner. class) and @ SpringBootTest annotations, add @ Test at the top of the Test method, and right-click the method to run it.

@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 to test and verify the normal use of the project. spring-boot-starter-test provides many basic usage methods, what's even more rare is that it adds support for Controller layer testing.

// Verify whether the result set is Assert. assertEquals (3, userMapper. getAll (). size (); // check the result set. The Assert prompt is displayed. 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 the Controller layer test. A simple example is as follows:

Public class HelloControlerTests {private MockMvc mvc; // initialization execution @ Before public void setUp () throws Exception {mvc = MockMvcBuilders. standaloneSetup (new HelloController ()). build () ;}// verify whether the controller responds normally and print the returned 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 determine whether the returned results are correct @ Test public void testHello () throws Exception {mvc. perform (MockMvcRequestBuilders. get ("/hello "). accept (MediaType. APPLICATION_JSON )). andExpect (status (). isOk ()). andExpect (content (). string (similar to ("Hello World ")));}}

Unit testing is the first barrier to verify your code. You need to develop the habit of performing unit testing for every part of the code you write. Do not wait until all the code is integrated before testing, after integration, because you pay more attention to the overall running effect, it is easy to omit the underlying bug of the Code.

Integration Test

After the overall development is complete, enter the integration test. the startup entry of the spring boot project is in the Application class. run the run method directly to start the project, however, during the debugging process, we must constantly debug the Code. If you need to manually restart the service every time you modify the code, it will be very troublesome, spring boot provides the support for hot deployment, which is convenient for debugging and use in web projects.

The following configurations must be added to pom:

<dependencies>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-devtools</artifactId>    <optional>true</optional>  </dependency></dependencies><build>  <plugins>    <plugin>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-maven-plugin</artifactId>      <configuration>        <fork>true</fork>      </configuration>    </plugin></plugins></build>

After the above configuration is added, the project supports hot deployment, which is very convenient for integration testing.

Put into production

In fact, I think this stage should be relatively simple and generally divided into two types; one is to package it into a jar package for direct execution, and the other is to package it into a war package and put it under the tomcat server.

Package into jar

If you are using maven to manage projects, you can run the following command:

Cd project and directory (same as pom. xml) mvn clean package # or execute the following command # exclude the test code and package mvn clean package-Dmaven. test. skip = true

After packaging, the jar package is generated in the target directory. The name is generally project name + version. jar

Start the jar package command

java -jar target/spring-boot-scheduler-1.0.0.jar

In this way, the service cannot be accessed as long as the console is disabled. The following code starts running in the background:

nohup java -jar target/spring-boot-scheduler-1.0.0.jar &

You can also choose to read different configuration files at startup.

java -jar app.jar --spring.profiles.active=dev

You can also set jvm parameters at startup.

java -Xms10m -Xmx80m -jar app.jar &gradle

If gradle is used, use the following command to package

gradle buildjava -jar build/libs/mymodule-0.0.1-SNAPSHOT.jar

Pack into war

The war package can be packaged in two ways. The first method is to export the war package using a development tool such as eclipse, and the other is to use commands. The second method is described here.

1. Modify the pom package for the maven Project

Set

<packaging>jar</packaging>

Change

<packaging>war</packaging>

2. Exclude tomcat during 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>

Set the scope attribute to provided, so that the JAR package is not included in the final WAR, because servers such as Tomcat and Jetty will provide related API classes at runtime.

3. register the startup class

Create ServletInitializer. java, inherit SpringBootServletInitializer, overwrite configure (), and register the startup class Application. When the external web Application Server constructs the Web Application Context, it adds the startup class.

public class ServletInitializer extends SpringBootServletInitializer {  @Override  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {    return application.sources(Application.class);  }}

Last executed

mvn clean package -Dmaven.test.skip=true

The project name + version number. war file is generated in the target directory and copied to the tomcat server for startup.

Gradle

If gradle is used, add war support to build. gradle to 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"  }}...

Then use the build command

gradle build

War is generated in the build \ libs directory.

Production O & M

View JVM parameter values

You can use the jinfo command that comes with java:

jinfo -flags pid

To check what gc, new generation, and old generation memory are used after the jar is started. The example is 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 number of parallel compilations-XX: initialHeapSize and-XX: MaxHeapSize: Specify the initial and maximum heap memory size of the JVM-XX: MaxNewSize: Maximum allocable size of the new generation memory in the JVM heap Area Small... -XX: + UseParallelGC: Garbage collection using the Parallel collector

How to restart

Simple and crude

Kill the process and start the jar package again.

Ps-ef | grep java # obtain the pidkill-9 pid of the Java program # restart Java-jar xxxx. jar again

Of course, this method is more traditional and violent, so we suggest you use the following method to manage

Script Execution

If maven is used, the following configuration must be included:

<plugin>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-maven-plugin</artifactId>  <configuration>    <executable>true</executable>  </configuration></plugin>

If gradle is used, the following configuration must be included:

springBoot {  executable = true}

Startup method:

1. You can directly start./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 a command.

Example of init. d:

ln -s /var/yourapp/yourapp.jar /etc/init.d/yourappchmod +x /etc/init.d/yourapp

In 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

Now, how to test, combine, and package springboot has been introduced. You can find time to study the automatic O & M of springboot and the use of spring boot and docker.

Sample Code-github

Sample Code-code cloud

Summary

The above is the spring boot testing package deployment method introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.