Spring Boot deployment and service configuration

Source: Internet
Author: User
Tags tmp folder

Spring Boot deployment and service configuration

Spring Boot is integrated with web containers by default. It is started by the main function entry just like a common Java program. Its built-in Tomcat container or Jetty container is determined by the configuration (default Tomcat ). Of course, you can also package the project into a war package and put it into an independent web Container (Tomcat, weblogic, and so on). Of course, you need to make simple adjustments to the program portal before that.

Maven or Gradle is used for project construction, which makes it very convenient to manage project dependencies, jar packages, and package deployment.

1. Embedded Server Configuration

After Spring Boot is built into the container, it modifies the related server configurations through the configuration file.
First, let's look at the following figure for the server configuration columns:

There are only a few common configurations, which are marked in purple. The area circled in red box can be understood by name classification.
Briefly describe several common configurations of the server:

# Project contextPath, generally in the official release, we do not configure the server. context-path =/myspringboot # error page, specify the URL to jump when an error occurs. Please refer to the BasicErrorController source code to learn about the server. error. path =/error # service port server. port = 9090 # maximum session Timeout (minutes). The default value is 30server. session-timeout = 60 # this service is bound to an IP address. When the server is started, if the local machine is not the IP address, an exception is thrown and the startup fails. It is configured only with Special Requirements # server. address = 192.168.16.11

Tomcat
Tomcat is the default container of Spring Boot. The following are some common configurations:

# Maximum number of tomcat threads. The default value is 200server. tomcat. max-threads = 800 # tomcat URI Encoding server. tomcat. uri-encoding = UTF-8 # Temporary Folder for storing Tomcat logs, Dump and other files, the default is the tmp folder of the system (such as: C: \ Users \ Shanhy \ AppData \ Local \ Temp) server. tomcat. basedir = H:/springboot-tomcat-tmp # Open the Tomcat Access log and set the log format: # server. tomcat. access-log-enabled = true # server. tomcat. access-log-pattern = # accesslog Directory, which is in basedir/logs # server by default. tomcat. accesslog. directory = # log file directory logging. path = H:/springboot-tomcat-tmp # Name of the log file. The default value is spring. loglogging. file = myapp. log

Jetty
If you want to select Jetty, It is very simple, that is, to exclude tomcat dependencies in pom and add the dependencies of the Jetty container, as shown below:

<code class=" hljs xml"><dependencies>  <dependency>    <groupid>org.springframework.boot</groupid>    <artifactid>spring-boot-starter-web</artifactid>    <exclusions>      <exclusion>        <groupid>org.springframework.boot</groupid>        <artifactid>spring-boot-starter-tomcat</artifactid>      </exclusion>    </exclusions>  </dependency>  <dependency>    <groupid>org.springframework.boot</groupid>    <artifactid>spring-boot-starter-jetty</artifactid>  </dependency><dependencies> </dependencies></dependencies></code>

Package
Packaging method:
Run CMD to enter the project directory and use the mvn clean package command to package. Take my project as an example:

E:\spring-boot-sample>mvn clean package

You can append the parameter-Dmaven. test. skip = true to skip the test.
The packaged files are stored in the target directory under the project, such as the spring-boot-sample-0.0.1-SNAPSHOT.jar.
Spring-boot-sample-0.0.1-SNAPSHOT.war if pom is configured with a war package

2. Deploy it to the JavaEE container to modify the startup class, inherit SpringBootServletInitializer, and rewrite the configure method.
public class SpringBootSampleApplication extends SpringBootServletInitializer{    private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {        return builder.sources(this.getClass());    }}
Modify the jar file in the pom file to war
<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%20%3Cpackaging%3Ejar%3C%2Fpackaging%3E%20%2D%2D%3E--><packaging>war</packaging></code>
Modify pom to exclude tomcat plug-ins
<code class=" hljs xml">        <dependency>            <groupid>org.springframework.boot</groupid>            <artifactid>spring-boot-starter-web</artifactid>            <exclusions>                <exclusion>                    <groupid>org.springframework.boot</groupid>                    <artifactid>spring-boot-starter-tomcat</artifactid>                </exclusion>            </exclusions>        </dependency></code>
Package and deploy to container
Use the command mvn clean package to package and deploy the package to a web Container like a J2EE project. 3. Use Profile to differentiate Environments

Spring boot can configure the profile in "configuration file", "Java code class", and "log configuration" to differentiate the execution results of different environments.

1. Configuration File
The configuration file application. yml and application. properties are different.
Using application. properties as an example, the file name is used to differentiate the environment application-{profile}. properties.
Application. properties

app.name=MyAppserver.port=8080spring.profiles.active=dev

Application-dev.properties

server.port=8081

Application-stg.properties

server.port=8082

When starting the program, add-spring. profiles. active = {profile} to specify the specific configuration.
For example, if we run java-jar demo. jar-spring. profiles. active = dev, how will the content in the above three files be applied?
Spring Boot loads the default configuration file first, and then overwrites the default configuration with the configuration in the specified profile.

App. name only exists in the default configuration file application. properties. Because the same configuration does not exist in the specified environment, this value will not be overwritten.
Server. port is 8080 by default. However, if we specify the environment, it will be overwritten. If the stg environment is specified, the value of server. port is 8082.
Spring. profiles. active specifies the dev environment by default. If we specify-spring. profiles. active = stg at runtime, the stg environment will be applied, and the final server. port value is 8082.

2. @ Profile annotation in the Java class
The following two different classes implement the same interface, and the @ Profile annotation specifies the specific environment

// Interface definition public interface SendMessage {// method definition public void send ();} // Dev Environment Implementation class @ Component @ Profile ("dev ") public class DevSendMessage implements SendMessage {@ Override public void send () {System. out. println (">>>>>>> Dev Send () <");}} // Stg Environment Implementation class @ Component @ Profile ("stg") public class StgSendMessage implements SendMessage {@ Override public void send () {System. out. println (">>>>>>> Stg Send () <");}} // start class @ SpringBootApplicationpublic class ProfiledemoApplication {@ Value ("$ {app. name} ") private String name; @ Autowired private SendMessage sendMessage; @ PostConstruct public void init () {sendMessage. send (); // the corresponding class will be instantiated according to the Environment specified by profile }}

3. logback-spring.xml also supports nodes to support Differentiation

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><configuration>    <include resource="org/springframework/boot/logging/logback/base.xml">    <logger name="org.springframework.web" level="INFO">    <springprofile name="default">        <logger name="org.springboot.sample" level="TRACE">    </logger></springprofile>    <springprofile name="dev">        <logger name="org.springboot.sample" level="DEBUG">    </logger></springprofile>    <springprofile name="staging">        <logger name="org.springboot.sample" level="INFO">    </logger></springprofile></logger></include></configuration></code>

Again, use logback-spring.xml instead of logback. xml for file names.

4. Specify an external configuration file

Some systems, such as databases or other third-party accounts, do not expose their configurations to developers due to security issues.
In this case, an external configuration file can be specified through parameters when running the program.
Take demo. jar as an example. The method is as follows:

java -jar demo.jar --spring.config.location=/opt/config/application.properties

The file name can be defined without any fixed requirements.

5. Create a Linux application's sh script

The following scripts are for reference only. make adjustments as needed.
Start. sh

#!/bin/shrm -f tpidnohup java -jar /data/app/myapp.jar --spring.profiles.active=stg > /dev/null 2>&1 &echo $! > tpid

Stop. sh

tpid=`cat tpid | awk '{print $1}'`tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`if [ ${tpid} ]; then        kill -9 $tpidfi

Check. sh

#!/bin/shtpid=`cat tpid | awk '{print $1}'`tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`if [ ${tpid} ]; then        echo App is running.else        echo App is NOT running.fi

Kill. sh

#! /Bin/sh # kill-9 'ps-ef | grep project name | awk' {print $2} ''kill-9' ps-ef | grep demo | awk '{ print $2 }''

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.