Project structure such as
One: System environment
This machine: 10.4.18.3
Server: 10.4.18.4, user name: WEB02
Two: Initializing the server environment
Create a directory on the server's home directory Deploy,deploy/profile
Mkdir-p/home/web01/deploy
Mkdir-p/home/web02/deploy/profile
Installing the JDK
Export java_home=/home/web02/jdk1.7.0_67
Three: Source code (This shows a self-written HTTP web server)
Com.lala.server.Server.java
Package Com.lala.server;import Java.io.ioexception;import Java.io.outputstream;import java.net.InetSocketAddress; Import Java.util.date;import java.util.hashmap;import Java.util.map;import Java.util.concurrent.executors;import Com.google.gson.gson;import Com.sun.net.httpserver.headers;import Com.sun.net.httpserver.httpexchange;import Com.sun.net.httpserver.httphandler;import Com.sun.net.httpserver.httpserver;public class Server {public void Httpserverservice () throws IOException {String hr = "=============================================================== ======="; System.out.println (""); SYSTEM.OUT.PRINTLN (HR); int port = 17002;inetsocketaddress addr = new inetsocketaddress (port); SYSTEM.OUT.PRINTLN ("HTTP Server start at" + Port + "..."); Httpserver Server = httpserver.create (addr, 0); Server.createcontext ("/gson", New Gsonhandler ()); System.out.println ("Create Path/gson"); Server.createcontext ("/index", New MyHandler ()); System.out.printlN ("Create Path/index"); Server.setexecutor (Executors.newcachedthreadpool ()); Server.start (); System.out.println ("Start HTTP server success at port [" + Port + "]"); SYSTEM.OUT.PRINTLN (HR);}} Class MyHandler implements HttpHandler {@SuppressWarnings ("deprecation") public void handle (Httpexchange Exchange) Throws IOException {Headers responseheaders = Exchange.getresponseheaders (); OutputStream responsebody = Exchange.getresponsebody (); Responseheaders.set ("Content-type", "text/html;charset=utf-8"); String html = "
Com.lala.server.Start.javaPackage Com.lala.server;import Java.io.ioexception;public class Start {public static void main (string[] args) throws Ioex ception {new Server (). Httpserverservice ();}}
Pom.xml<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >< modelversion>4.0.0</modelversion><groupid>com.lala</groupid><artifactid>profile< /artifactid><version>0.0.1</version><packaging>jar</packaging><name>profile </name><url>http://maven.apache.org</url><properties><project.build.sourceencoding >UTF-8</project.build.sourceEncoding></properties><dependencies><dependency>< Groupid>junit</groupid><artifactid>junit</artifactid><version>4.10</version> <scope>test</scope></dependency><dependency><groupid>org.postgresql</groupid ><artifactid>postgresql</artifactid><version>9.3-1102-jdbc4</version></ Dependency><dependency><groupid>com.google.code.gson</groupid><artifactid>gson</artifactid><version>2.3.1 </version></dependency></dependencies><profiles><profile><id>dev</id ><properties><env>dev</env></properties><activation><activeByDefault> true</activebydefault></activation></profile><!--Test Suit--><profile><id>test </id><properties><env>test</env></properties></profile><!--Production-->< Profile><id>production</id><properties><env>production</env></properties ></profile></profiles><build><resources><resource><directory>${ Project.basedir}/src/main/resources/${env}</directory><includes><include>*.*</include> </includes><filtering>true</filtering></resource><resource><directory>${ project.basedir}/src/main/resources/</directory><includes><include>logback.xml</include></includes>< filtering>true</filtering></resource></resources><plugins><plugin>< Artifactid>maven-compiler-plugin</artifactid><version>3.2</version><configuration> <source>1.7</source><target>1.7</target></configuration></plugin>< plugin><groupid>org.apache.maven.plugins</groupid><artifactid>maven-war-plugin</ artifactid><version>2.5</version><configuration><warname>tiles</warname>< archive><addmavendescriptor>false</addmavendescriptor></archive><webresources>< Resource><directory>src/main/resources/${env}/application.properties</directory><filtering >true</filtering></resource></webResources></configuration></plugin>< Plugin><groupid>org.apache.maven. plugins</groupid><artifactid>maven-jar-plugin</artifactid><version>2.5</version ><configuration><archive><manifest><addClasspath>true</addClasspath>< Classpathprefix>/home/web02/deploy/profile/current/lib/</classpathprefix><mainclass> Com.lala.server.start</mainclass></manifest></archive></configuration></plugin> <plugin><groupid>org.apache.maven.plugins</groupid><artifactid>maven-dependency-plugin </artifactid><version>2.9</version><executions><execution><id>copy</id ><phase>package</phase><goals><goal>copy-dependencies</goal></goals> <configuration><outputDirectory>${project.build.directory}/lib</outputDirectory>< excludetransitive>false</excludetransitive><stripversion>false</stripversion></ Configuration></execution></executionS></plugin></plugins></build></project>
deploy.sh#!/bin/shecho "============*******************=================" echo "============ Java Automatic deployment script =================" echo "============*******************=================" Read-p "Enter the IP to be deployed (for example: 10.4.18.4):" Ipread-p "Enter the branch name of the deployment (for example: Master): "Branchread-p" Enter the deployed environment (for example: Product|test|dev): "Envread-p" Please enter the program action (for example: start|stop|restart|info|status): " Handleread-p "Whether you need pull code from a remote warehouse (for example: y|n):" pullip=${ip:-10.4.18.4}branch=${branch:-master}env=${env:-dev}handle=${ Handle:-restart}pull=${pull:-n}echo $ip $branch $env $handle $pulluser =web02applicationname=profilemyproject=. rootdir=/home/${user}/deployproject= $rootDir/$applicationNameappName = $applicationName -0.0.1.jarjar_file=$ myproject/target/$appNameif [$pull = = ' y '];then git checkout $branch git pull Origin $branchfimvn clean package-p ${env}scp-r target/lib [email protected] $ip: $project/scp $jar _file deploy/apiservice.sh [email protected] $IP: $project/ssh [email protected] $ip sh $project/apiservice.sh $handle $project $AppName
deploy/apiservice.sh#!/bin/sh# WARNING!!! : The script Stop section uses the System Kill command to force the termination of the specified Java program process. #在杀死进程前, no condition checks were made. In some cases, such as a program is in the process of file or database write operations, #可能会造成数据丢失或数据不完整. If you have to take this into account, you will need to overwrite this script, java_home=/home/web02/jdk1.7.0_67# the system user that the execution program starts, and the root account is not recommended for security reasons running_user=web02# The directory in which the Java program resides (the top-level directory of classes) app_home=$2# the Java Main program (Main method Class) that needs to be started App_mainclass=$3#java the virtual machine startup Parameters java_opts= "-ms512m- MX512M-XMN256M-DJAVA.AWT.HEADLESS=TRUE-XX:MAXPERMSIZE=128M-XDEBUG-XRUNJDWP:TRANSPORT=DT_SOCKET,ADDRESS=17003, Server=y,suspend=n "Mkdir-p $APP _home/releasemkdir-p $APP _home/currentreleasefile= $APP _home/release/$APP _ mainclass-' Date ' +%y-%m-%d_%h:%m:%s ' #备份之前的代码cp-R $APP _home/$APP _mainclass $releaseFilerm-rf $APP _home/current/$ APP_MAINCLASSRM-RF $APP _home/current/libln-s $releaseFile $APP _home/current/$APP _mainclassrm-rf $APP _home/$APP _ MAINCLASSMV $APP _home/lib $APP _home/current/cd $APP _home/currentpsid=0checkpid () {javaps= ' $JAVA _home/bin/jps-l | grep $APP _mainclass ' If [-N ' $javaps]; Then psid= ' echo $javaps | awk ' {print '} ' else psid=0 fi}#################################### (function) Start Program # Description: #1. First call the Checkpid function and refresh the $PSID global variable # #. If the program has started ($psid not equal to 0), the prompt program has started # #. If the program is not started, execute the start command line # #. After starting the command execution, call the Checkpid function again # #. If the result of step 4 is able to confirm the PID of the program, print [OK], otherwise print [Failed] #注意: Echo-n means that after the character is printed, the line is not wrapped ################################## #start () { Checkpid if [$psid-ne 0]; Then echo "================================" echo "warn: $APP _mainclass already started! (pid= $psid) "echo" ================================ "Else Echo-n" starting $APP _mainclass ... "Nohup $JAVA _h Ome/bin/java $JAVA _opts-jar $APP _home/current/$APP _mainclass & Checkpid If [$psid-ne 0]; Then echo "(pid= $psid) [OK]" Else echo "[Failed]" fi fi}################################### #说明 : #1. First call the Checkpid function and refresh the $PSID global variable # #. If the program has started ($psid not equal to 0), start execution Stop, otherwise the prompt program does not run # #. Use the kill-9 PID command to force kill process # #. Immediately after executing the KILL command line, look at the return value of the previous command: $? #5. If the result of step 4 is $ = 0, print [OK], otherwise print [Failed] #6. In order to prevent the Java program from being started multiple times, the process of repeated checking is added here (recursive call to stop). #注意: In Shell programming, "$?" Represents the return value of the previous command or a function ################################## #stop () {checkpid if [$psid-ne 0]; then echo-n "Stopping $APP _mainclass ... (pid= $psid) "Kill-9 $psid if [$?] -eq 0]; Then echo "[OK]" Else echo "[Failed]" fi checkpid if [$psid-ne 0]; Then stop fi else echo "================================" echo "warn: $APP _mainclass was not Runni Ng "echo" ================================ "fi}################################### #说明: #1. First call the Checkpid function and refresh the $PSID global variable # #. If the program has started ($psid not equal to 0), the prompt is running and indicates pid#3. Otherwise, the prompt program does not run ################################## #status () {checkpid if [$psid-ne 0]; Then echo ' $APP _mainclass is running! (pid= $psid) "Else echo" $APP _mainclass is not running "fi}#################################### (function) printing system environment parameter ####### ########################### #info () {echo "System information:" echo "****************************" Echo ' Head-n 1 /etc/issue ' echo ' uname-a ' ECHo echo "java_home= $JAVA _home" Echo ' $JAVA _home/bin/java-version ' echo Echo ' app_home= $APP _home ' echo ' App_main class= $APP _mainclass "echo" **************************** "}################################### #读取脚本的第一个参数 ($), Make a judgment # parameter value range: {start|stop|restart|status|info} #如参数不在指定范围之内, print help ################################## #case "$" in ' Start ') Start; ' Stop ') stop; ' Restart ') stop start;; ' status ') status; ' info ') info;; *) echo "Usage: $ {start|stop|restart|status|info}" exit 1esacexit 0
Four: Precautions1:pom.xml inside the/home/web02/deploy/profile/current/lib/need to be consistent with the server's publishing directory, or you will not find the jar
2:pom.xml inside the Profiles configuration usage, please refer to my previous blog
V: Usage
Go to the root directory of the project to execute
SH deploy.sh automatic deployment (post, restart) as prompted
After the publication is successful, enter in the browser
Http://10.4.18.4:17002/index
Http://10.4.18.4:17002/gson
You can see the results
Automatically deploy (publish, restart) Maven (Java) projects using shell scripts