Spring Boot deployment and service configuration

Spring Boot is integrated with the web container by default, and the startup method is started by the main function entry like a normal Java program. Its built-in Tomcat container or Jetty container is determined by configuration (default Tomcat). Of course, you can also package the project into a war package and put it in a separate web container (Tomcat, weblogic, etc.), of course, you need to make simple adjustments to the program entry before this.

We use Maven or Gradle for project construction, which will make project dependencies, jar package management, and package deployment very convenient.

1. Embedded Server Configuration

After Spring Boot builds the container, it modifies the relevant server configuration by means of configuration files.
Let's take a look at the figure below, for the configuration items about the server:
Configuration
Configuration

Among them, there are only a few commonly used configurations, which have been marked with purple. The part circled by the red frame can be understood by looking at the name classification.
A brief description of several common configurations of the server:

# Project contextPath, generally in the official release version, we do not configure
server.context-path=/myspringboot
# Error page, specify the URL to jump when an error occurs. Please check the BasicErrorController source code to know
server.error.path=/error
# Service port
server.port=9090
# The maximum session timeout time (minutes), the default is 30
server.session-timeout=60
# The service is bound to an IP address. When starting the server, if the local machine is not the IP address, an exception will be thrown and the startup will fail. It is only configured under special needs.
# server.address=192.168.16.11

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

# The maximum number of threads of tomcat, the default is 200
server.tomcat.max-threads=800
# URI encoding of tomcat
server.tomcat.uri-encoding=UTF-8
# Store Tomcat logs, dumps and other files Temporary folder, the default is the system's tmp folder (eg: C:\Users\Shanhy\AppData\Local\Temp)
server.tomcat.basedir=H:/springboot-tomcat-tmp
# Open Tomcat's Access log, and The method of setting the log format:
#server.tomcat.access-log-enabled=true
#server.tomcat.access-log-pattern=
# accesslog directory, the default is basedir/logs
#server.tomcat.accesslog.directory=
# log File directory
logging.path=H:/springboot-tomcat-tmp
# Log file name, the default is spring.log
logging.file=myapp.log

Jetty
如果你要选择Jetty,也非常简单,就是把pom中的tomcat依赖排除,并加入Jetty容器的依赖,如下:

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

打包
Packaging method:
CMD enter the project directory, use the mvn clean package command to package, take my project as an example:

E:\spring-boot-sample>mvn clean package
1
1
You can add the parameter -Dmaven.test.skip=true to skip test.
The packaged file is stored in the target directory under the project, such as: spring-boot-sample-0.0.1-SNAPSHOT.jar
If the pom is configured with a war package, it is spring-boot-sample-0.0.1-SNAPSHOT. war

2. Deploy to JavaEE container

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());
























Spring boot can configure profiles in " configuration

files", "Java code classes", and "log configuration" to distinguish different environments and execute different results properties For example, the environment is distinguished by the file name application-{profile}.properties application.properties app.name=MyApp server.port=8080 spring.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 used. For example we execute java -jar demo.jar –spring.profiles.active=dev Then the above 3 How will the content of this file be used? Spring Boot will first load the default configuration file, and then use the configuration in the specified profile to override the default configuration. app.name only exists in the default configuration file application.properties, because the same configuration does not exist in the specified environment, so this value will not be overwritten





















server.port defaults to 8080, but after we specify the environment, it will be overridden. If the stg environment is specified, the 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 value of server.port is 8082
2 , @Profile annotation in Java class
The following two different classes implement the same interface, @Profile annotation specifies 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()<<<<< <<<");







public class StgSendMessage implements SendMessage {

    @Override
    public void send() {
        System.out.println(">>>>>>>>Stg Send()<<<<<<<<");
    }

}

// Startup class
@SpringBootApplication
public class ProfiledemoApplication {

    @Value("${app.name}")
    private String name;

    @Autowired
    private SendMessage sendMessage;

    @PostConstruct
    public void init(){
        sendMessage.send();// According to the environment specified by profile Instantiate the corresponding class
    }

}

3. logback-spring.xml also supports nodes to support 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> exposed to developers.4. Specify external configuration files Some

Don't use logback.xml for the file name, please use logback-spring.xml




In this case, when we run the program, we can specify an external configuration file through parameters.
Take demo.jar as an example, the method is as follows:

java -jar demo.jar --spring.config.location=/opt/config/application.properties
1
1
The file name is freely defined, and there is no fixed requirement.

5. Create a sh script for a Linux application The

following scripts are for reference only, please adjust according to your needs
start.sh

#!/bin/sh

rm -f tpid

nohup java -jar myapp.jar --spring.config.location =application.yml > /dev/null 2>&1 &

echo $! > tpid

echo Start Success!

stop.sh

#!/bin/sh
APP_NAME=myapp

tpid=`ps -ef|grep $APP_NAME|grep -v grep| grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
    echo 'Stop Process...'
    kill -15 $tpid
fi
sleep 5
tpid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
    echo 'Kill Process!'
    kill -9 $tpid
else
    echo 'Stop Success!'
fi

check.sh

#!/bin/sh
APP_NAME=myapp

tpid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
        echo 'App is running.'
else
        echo 'App is NOT running.'
fi

kill.sh

#!/bin/sh
APP_NAME=myapp

tpid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
    echo 'Kill Process!'
    kill -9 $tpid
fi

6. Start, stop and restart using Linux services

1. First configure the plugin in pom.xml

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

pay special attention to <executable>true</executable >

2. Then use mvn clean package -Dmaven.test.skip=true normally to make the project into a jar package

3. Upload the jar package to the server, assuming the deployment path is /var/apps/myapp. jar, use the command to make a soft link to the /etc/init.d directory, the command:

ln -s /var/apps/myapp.jar /etc/init.d/myapp
1
1
where myapp at the end of /etc/init.d/myapp can be another name, this is the service name, we will use service [service name] start to start (described below).

4. Grant executable permission to the jar file, command:

chmod +x myapp.jar
1
1
5. Next, you can use the familiar service myapp start|stop|restart|status to start and stop the application.
After executing the command, you will get the result feedback in the form of Started|Stopped [PID].
Default PID file path: /var/run/appname/appname.pid
Default service log file path: /var/log/appname.log (LOG_FOLDER can be modified by the following .conf method)

6. Use a custom .conf file to To change the default configuration, the method is as follows:
create a .conf file in the same path as the jar package, the name should be the same as the name of the .jar, such as myapp.conf (if the jar file we packaged is myapp-1.0.0.jar then here conf file should also be myapp-1.0.0.conf), its content configuration can be as follows:

JAVA_HOME=/usr/local/jdk
JAVA_OPTS=-Xmx1024M
LOG_FOLDER=/data/logs/myapp

Note: The folder directory corresponding to LOG_FOLDER must exist. If the directory does not exist, the service will not automatically create the directory.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326397641&siteId=291194637