Gradle学习之部署上传项目

Stella981
• 阅读 430

 原先在公司做项目时,写了一个简单的基于gradle部署项目的脚本,今天翻出来记录一下 

一、build.gradle

Gradle学习之部署上传项目 Gradle学习之部署上传项目

buildscript {
    ext {
        env = System.getProperty("env") ?: "test"
        jvmArgs = "-server -Xms128m -Xmx128m -XX:NewRatio=4  -XX:SurvivorRatio=16 -XX:MaxTenuringThreshold=15 -XX:CMSInitiatingOccupancyFraction=80 -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled  -XX:+ExplicitGCInvokesConcurrent -XX:+DoEscapeAnalysis -XX:-HeapDumpOnOutOfMemoryError"
        if (env == "prod") {
            jvmArgs = "-server -Xms2g -Xmx2g -XX:NewRatio=4  -XX:SurvivorRatio=16 -XX:MaxTenuringThreshold=15 -XX:CMSInitiatingOccupancyFraction=80 -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled  -XX:+ExplicitGCInvokesConcurrent -XX:+DoEscapeAnalysis -XX:-HeapDumpOnOutOfMemoryError"
        }
        userHome = System.getProperty("user.home")
        osName = System.getProperty("os.name")
    }

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.hidetake:gradle-ssh-plugin:2.7.0'
        classpath 'co.tomlee.gradle.plugins:gradle-thrift-plugin:0.0.6'
    }
}

allprojects {
    apply plugin: 'idea'
    apply plugin: 'eclipse'
    apply plugin: 'org.hidetake.ssh'
    group = 'com.mwee.information.core'
    version = '1.0-SNAPSHOT'
    ssh.settings {
        timeoutSec = 60
        knownHosts = allowAnyHosts
    }
    defaultTasks 'clean', 'copyPartDependencies'

    //排除Log4j依赖
    configurations {
        compile.exclude module: 'slf4j-log4j12'
        compile.exclude module: 'org.apache.logging.log4j'
        compile.exclude module: 'log4j'
        all*.exclude group: 'org.apache.logging.log4j'
        all*.exclude group: 'log4j'
    }


}

subprojects {
    apply plugin: 'java'
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    repositories {
        mavenLocal()
        maven { url "http://114.80.88.52:9001/nexus/content/groups/public/" }
    }
    sourceSets {
        main {
            java {
                srcDirs = ['src/main/java']
            }
            resources {
                srcDirs = ["src/main/resources", "src/main/profile/$env"]
            }
        }
    }
    dependencies {
        compile("org.codehaus.groovy:groovy-all:2.2.1")
        compile 'org.codehaus.groovy:groovy-backports-compat23:2.4.5'
        compile("org.springframework.boot:spring-boot-starter-web:1.4.2.RELEASE")
        compile("org.apache.commons:commons-lang3:3.4")
        compile("org.apache.commons:commons-collections4:4.1")
        compile "org.apache.commons:commons-pool2:2.4.2"
        compile group: 'com.alibaba', name: 'fastjson', version: '1.2.12'
        // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.6'
        // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
        compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.6'
        compile group: 'org.aspectj', name: 'aspectjrt', version: '1.8.7'
        compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.7'
        compile group: 'com.thoughtworks.xstream', name: 'xstream', version: '1.4.1'
        compile(group: 'org.mortbay.jetty', name: 'jetty', version: '6.1.26')
        compile group: 'org.projectlombok', name: 'lombok', version: '1.16.8'
        compile group: 'com.squareup.okhttp', name: 'okhttp', version: '2.7.5'
        compile group: 'com.google.guava', name: 'guava', version: '18.0'
        compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
        compile group: 'com.jcraft', name: 'jsch', version: '0.1.53'
        testCompile group: 'junit', name: 'junit', version: '4.12'
        testCompile "org.springframework:spring-test:4.3.4.RELEASE"
        compile "javax.validation:validation-api:1.1.0.Final"
        compile "org.hibernate:hibernate-validator:5.2.4.Final"
    }
    //gradle utf-8 compile
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
    }

    task copyAllDependencies(type: Copy, dependsOn: jar) {
        description = "拷贝全部依赖的jar包"
        from configurations.runtime
        into 'build/libs'
    }

    task copyPartDependencies(type: Copy, dependsOn: jar) {
        description = "拷贝部分依赖的jar"
        from configurations.runtime
        into 'build/libs'
        doLast {
            file("build/libs").listFiles({ !it.name.endsWith("-SNAPSHOT.jar") } as FileFilter).each {
                it.delete()
            }
        }

    }

}

View Code

二、对应模块下的build.gradle

Gradle学习之部署上传项目 Gradle学习之部署上传项目

def mainClass = "com.hzgj.information.rest.user.run.UserServiceProvider"
def appHome = "/home/appsvr/apps/rest_user"
def javaCommand = "nohup java $jvmArgs -Djava.ext.dirs=$appHome/libs -Denv=$env  $mainClass >$appHome/shell.log 2>&1 &"
def index = System.getProperty("index")


def remote = remotes {
    test_0 {
        role 'test_0'
        host = '10.0.21.152'
        if (file("$userHome/.ssh/id_rsa").exists()) {
            user = 'appsvr'
            identity = file("$userHome/.ssh/id_rsa")
        } else {
            user = 'appsvr'
            password = 'xxx'
        }

    }


    test_1 {
        role 'test_1'
        host = '10.0.146.20'
        if (file("$userHome/.ssh/id_rsa").exists()) {
            user = 'appsvr'
            identity = file("$userHome/.ssh/id_rsa")
        } else {
            user = 'appsvr'
            password = 'xxx'
        }
    }
    home {
        role 'home'
        host = '192.168.109.130'
        user = 'appsvr'
        password = 'xxx'
        // identity = file('id_rsa')
    }


}
task deploy << {
    description = "拷贝jar包并启动java服务"
    def roles = remote.findAll {
        def currentEnv = index == null ? "$env" : "$env" + "_" + index
        it['roles'][0].toString().contains(currentEnv)
    }
    ssh.run {
        roles.each {
            def role = it['roles'][0].toString()
            session(remotes.role(role)) {
                try {
                    execute("ls $appHome")
                } catch (Exception e) {
                    println("#############目录[$appHome]不存在,将自动创建############")
                    execute("mkdir -p $appHome")
                }
                finally {
                    def r = '$1'
                    def pid = execute("jps -l |grep '$mainClass' |awk \'{print $r}\'")
                    if (pid) {
                        execute("kill -9 $pid")
                    }
                    put from: 'build/libs', into: "$appHome"
                    println("###############准备启动java服务[$javaCommand]####################")
                    execute("$javaCommand")
                    sleep(10000)
                    pid = execute("jps -l |grep '$mainClass' |awk \'{print $r}\'")
                    if (pid) {
                        println("#####$mainClass [$pid] 启动成功...######")
                        execute("rm -f $appHome/shell.log")
                    } else {
                        println("#$mainClass 启动失败...输出日志如下:#")
                        execute("cat $appHome/shell.log")
                    }
                }
            }
        }

    }
}

task stop << {
    def roles = remote.findAll {
        def currentEnv = index == null ? "$env" : "$env" + "_" + index
        it['roles'][0].toString().contains(currentEnv)
    }
    ssh.run {
        roles.each {
            session(remotes.role("$env")) {
                def r = '$1'
                def pid = execute("jps -l |grep '$mainClass' |awk \'{print $r}\'")
                if (pid) {
                    execute("kill -9 $pid")
                }
            }
        }
    }
}
task start << {
    def roles = remote.findAll {
        def currentEnv = index == null ? "$env" : "$env" + "_" + index
        it['roles'][0].toString().contains(currentEnv)
    }
    ssh.run {
        roles.each {
            def role = it['roles'][0].toString()
            session(remotes.role(role)) {
                def r = '$1'
                def pid = execute("jps -l |grep '$mainClass' |awk \'{print $r}\'")
                if (pid) {
                    execute("kill -9 $pid")
                }
                println("###############准备启动java服务[$javaCommand]####################")
                execute("$javaCommand")
                sleep(10000)
                pid = execute("jps -l |grep '$main Class' |awk \'{print $r}\'")
                if (pid) {
                    println("#$mainClass [$pid] 启动成功...#")
                    execute("rm -f $appHome/shell.log")
                } else {
                    println("#$mainClass 启动失败...输出日志如下:#")
                    execute("cat $appHome/shell.log")
                }
            }
        }
    }


}

View Code

三、使用方式

1.先运行gradle copyAll -x test 进行打包操作,该操作会将该模块所有的依赖的jar

2.进入到对应的模块下 运行gradle deploy -Denv=xxx -Dindex=xxx ,什么意思呢?-Denv代表哪一个环境 -Dindex指定该环境下哪个节点进行发布

3.gradle start -Denv=xxx -Dindex=xxx 运行当前环境下的应用

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
2021 最顶级 React 组件库推荐
点上方蓝字关注公众号「前端从进阶到入院」作者丨MaxRozen译者丨王强策划丨小智AntDesign!(https://oscimg.oschina.net/oscnet/a85c35f23bd04e5da6a1e5e68a24119b.png)项目链接:AntDesignh
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
可莉 可莉
2年前
2021 最顶级 React 组件库推荐
点上方蓝字关注公众号「前端从进阶到入院」作者丨MaxRozen译者丨王强策划丨小智AntDesign!(https://oscimg.oschina.net/oscnet/a85c35f23bd04e5da6a1e5e68a24119b.png)项目链接:AntDesignh
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这