deployJar.groovy 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env groovy
  2. /**
  3. * 一键发布 SpringBoot jar 到远程 Linux 主机
  4. * 依赖环境变量(Jenkinsfile 的 environment {} 已定义即可):
  5. * JAR_NAME 例:jeecg-system-start-3.8.2.jar
  6. * JAR_PATH 例:sohoyw-som/jeecg-module-system/jeecg-system-start/target/${JAR_NAME}
  7. * REMOTE_HOST 例:root@52.83.132.95
  8. * REMOTE_PORT 例:8080
  9. * REMOTE_PATH 例:/srv/server
  10. * profile 例:test
  11. *
  12. * 用法:
  13. * deploySpringBoot()
  14. * 或
  15. * deploySpringBoot(jarName: 'xxx.jar', profile: 'prod')
  16. */
  17. def call(Map args = [:]) {
  18. /* 0. 读取参数(优先使用传参,其次 fallback 到环境变量) */
  19. String jarName = args.jarName ?: env.JAR_NAME
  20. String jarPath = args.jarPath ?: env.JAR_PATH
  21. String remoteHost= args.remoteHost?: env.REMOTE_HOST
  22. String remotePort= args.remotePort?: env.REMOTE_PORT
  23. String remotePath= args.remotePath?: env.REMOTE_PATH
  24. String profile = args.profile ?: env.profile
  25. String remoteJar = "${remotePath}/${jarName}"
  26. echo ">>> 开始发布 ${jarName} 到 ${remoteHost}:${remotePort}"
  27. /* 1. 停旧服务(端口进程) */
  28. sh """
  29. ssh -o StrictHostKeyChecking=no ${remoteHost} \
  30. 'lsof -ti:${remotePort} | xargs -r kill -9 || true'
  31. """
  32. /* 2. 备份旧包(如果存在) */
  33. sh """
  34. ssh -o StrictHostKeyChecking=no ${remoteHost} \
  35. 'test -f ${remoteJar} && \\
  36. mv ${remoteJar} ${remoteJar}-\$(date +%Y%m%d%H%M) || true'
  37. """
  38. /* 3. 传新包 */
  39. sh "scp -o StrictHostKeyChecking=no ${jarPath} ${remoteHost}:${remoteJar}"
  40. /* 4. 启动新服务 */
  41. sh """
  42. ssh -o StrictHostKeyChecking=no ${remoteHost} \
  43. 'cd ${remotePath} && nohup java -jar ${jarName} \
  44. --spring.profiles.active=${profile} > server.log 2>&1 &'
  45. """
  46. echo "<<< 发布完成"
  47. }