1. 程式人生 > 實用技巧 >Gradle指令碼部署SpringBoot應用到遠端伺服器

Gradle指令碼部署SpringBoot應用到遠端伺服器

引入hidetake.ssh外掛

buildscript {
    repositories {
        mavenLocal()
        maven { url "https://maven.aliyun.com/repositorys/public/" }
        maven { url "https://repo.spring.io/milestone" }
        maven {
            url 'https://plugins.gradle.org/m2/'
        }
    }
    dependencies {
        classpath 'org.hidetake:gradle-ssh-plugin:2.6.0'
    }
}
apply plugin: 'org.hidetake.ssh'

指定可執行Jar的主類

bootJar { // 允許打成可執行jar
    enabled = true
}
jar {
    manifestContentCharset 'utf-8'
    metadataCharset 'utf-8'
    manifest {
        attributes "Main-Class": "com.xxx.dataservice.api.ApiApplication" // 入口類路徑
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

設定遠端伺服器的資訊

ssh.settings {  // 允許任何主機進行連線
    knownHosts = allowAnyHosts
}

remotes {
    deployServer { 
        host = '127.0.0.1'
        user = 'root'
        password = 'root'
    }
}

設定伺服器部署目錄和執行的指令碼

def remoteDir = '/opt/xxx/' // 伺服器部署目錄

def jarName = archivesBaseName + '-' + this.getVersion() + '.jar'; // 打包的jar包的名稱

// 以下程式碼是執行指令碼,在jar包上傳後,需要執行這段指令碼來重啟應用
// 當然你可以把這段指令碼寫在.sh檔案中,之後把這個.sh檔案放到伺服器上執行
def shell = '''
cd '''+remoteDir+'''
APP_NAME='''+jarName+'''
#重啟命令
pid=`ps -ef | grep $APP_NAME | grep -v grep |awk '{print $2}'`
if [ $pid ]; then
    echo :App  is  running pid=$pid
    kill -9 $pid
fi
nohup nohup java -jar -Dspring.profiles.active=test $APP_NAME > log.log & 
tail -f /opt/xxx/log.log
'''

編寫部署指令碼

task remoteDeploy(dependsOn: [clean, bootJar]) {
    bootJar.mustRunAfter clean
    doLast {
        ssh.run {
            session(remotes.getByName('deployServer')) {
                println '>>> start copying jar...'
                put from: libsDir.toString() +'\\'+jarName, into: remoteDir // 將jar包上傳上去
                println '>>> start app... '
                // 上傳完成後執行重啟指令碼
                executeScript '''
                '''+shell+''' 
                '''
                //execute 'sh '+remoteDir+'/restart.sh'
                println '>>> remote deploy OK...'
            }
        }
    }
}