Spring Boot Deployment and service configuration

Source: Internet
Author: User
Tags tmp folder shebang

Spring Boot is an integrated Web container by default and starts in the same way as a normal Java program, starting with the main function entry. Its built-in tomcat container or jetty container, which is determined by the configuration (default tomcat). Of course you can also package the project into a war package, put it into a separate web container (Tomcat, WebLogic, and so on), of course, before you make a simple adjustment to the program portal.

Project Building we use MAVEN or Gradle, which makes project dependencies, jar package management, and package deployment very convenient.

One, embedded Server configuration

Spring boot uses the configuration file to modify the relevant server configuration after it is built into the container.
Let's take a look at the following diagram for a configuration column entry for the server:

Only a few of the commonly used configurations have been marked with purple. Red-framed parts, look at the name classification can understand its role.
Make a brief description of several commonly used configurations of the server:

# 项目contextPath,一般在正式发布版本中,我们不配置server.context-path=/myspringboot# 错误页,指定发生错误时,跳转的URL。请查看BasicErrorController源码便知server.error.path=/error# 服务端口server.port=9090# session最大超时时间(分钟),默认为30server.session-timeout=60# 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置# server.address=192.168.16.11

Tomcat
Tomcat is the default container for spring boot, and here are a few common configurations:

# Tomcat Maximum number of threads, default isserver.tomcat.max-threads= -# tomcat URI encodingserver.tomcat.uri-encoding=UTF-8# A temporary folder for files such as Tomcat logs, dumps, and so on, default to the system's TMP folder (for example: C:\Users\Shanhy\AppData\Local\Temp)Server.tomcat.basedir=H:/springboot-tomcat-tmp# Open the Tomcat access log, and you can set the method for the log format:#server. Tomcat.access-log-enabled=true#server. tomcat.access-log-pattern=# Accesslog directory, default in Basedir/logs#server. tomcat.accesslog.directory=# log file directoryLogging.path=H:/springboot-tomcat-tmp# log file name, default is Spring.logLogging.file=myapp.log

Jetty
If you are going to choose jetty, it is also very simple to exclude the Tomcat dependency in Pom and add the dependency of the jetty container as follows:

<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> 

Packing
Packaging method:
CMD into the project directory, using the MVN Clean Packages command to package, take my project projects 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: Spring-boot-sample-0.0.1-snapshot.jar
Spring-boot-sample-0.0.1-snapshot.war If the POM is configured with a war package

Ii. deploy to a Java EE container
    1. Modify the startup class, Inherit Springbootservletinitializer, and override the Configure method
publicclass SpringBootSampleApplication extends SpringBootServletInitializer{    privatestaticfinal Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);    @Override    protectedconfigure(SpringApplicationBuilder builder) {        return builder.sources(this.getClass());    }}
    1. Modify the jar in the Pom file as war
<!-- <packaging>jar</packaging> --><packaging>war</packaging>
    1. Modify Pom to exclude Tomcat plugins
        <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>
    1. Package deployment to a container
      Use the command MVN clean package to deploy to a web container just like a generic Java EE project.
Iii. using profile to differentiate the environment

Spring boot can configure profiles to differentiate between different environments and perform different results in "Configuration Files", "Java Code Classes", "Log Configuration"

1. Configuration files
Using configuration files Application.yml and application.properties differ
Take Application.properties as an example to differentiate the environment by file name 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

Specify the specific configuration to use when starting the program by adding –spring.profiles.active={profile}
For example, if we execute Java-jar demo.jar–spring.profiles.active=dev, then how will the contents of the above 3 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 exists only in the default profile application.properties because the same configuration does not exist in the specified environment, so the value is not overwritten
Server.port defaults to 8080, but when we specify an environment, it will be overwritten. If the STG environment is specified, the Server.port is 8082
spring.profiles.active Specifies the dev environment by default, and if we specify –SPRING.PROFILES.ACTIVE=STG at run time, the STG environment is applied and the final Server.port value is 8082

2. @profile annotations in Java class
The following 2 different classes implement the same interface, @Profile annotations specify the specific environment

//Interface Definition Public  interface SendMessage {    //Send SMS 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 () <<<<<<<<"); }}//Startup class@SpringBootApplication Public  class profiledemoapplication {    @Value("${app.name}")PrivateString name;@Autowired    PrivateSendMessage 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 support the node to support the distinction

<?xml version= "1.0" encoding= "UTF-8"?><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" />    </springprofile>    <springprofile name="Dev">        <logger name="Org.springboot.sample" level ="DEBUG" />    </springprofile>    <springprofile name="Staging">        <logger name="Org.springboot.sample" level ="INFO" />    </springprofile></configuration>

Again, do not use the Logback.xml file name. Use Logback-spring.xml

Iv. specifying the external configuration file

Some systems, such as information about databases or other third-party accounts, are not configured to be exposed to developers in the project because of security issues.
In this case, when we run the program, we can specify an external configuration file through the parameters.
Taking Demo.jar as an example, the method is as follows:

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

Where the file name is arbitrarily defined, no fixed requirements.

V. Create an SH script for a Linux application

The following scripts are for reference only, please make adjustments according to your needs
start.sh

#!/bin/sh-f2>&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/sh‘{print $1}‘$tpid‘{print $2}‘$tpid`if${tpid}then        echo App is running.else        echo App is NOT running.fi

kill.sh

#!/bin/sh# kill -9 `ps -ef|grep 项目名称|awk ‘{print $2}‘`kill -9‘{print $2}‘`

Spring Boot Deployment and service configuration

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.