java自实现项目部署

java自实现项目部署

使用docker拉了一套jenkins环境,配置好了svn但是运行一直有问题。后面想想,自实现部署项目也不是很难,还不如自己写一套.

实现逻辑:

1.服务器上编写运行脚本,指定包存放位置

2.编写一套部署代码,将本地jar包上传到服务器指定位置

3.本地maven package打包后将该包通过部署模块上传到服务器,并备份,执行脚本

按照如上逻辑后来看看具体实现方法。

编写运行脚本

vim task

#!/usr/bin/env bash

JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-0.el8_4.x86_64
PATH=${JAVA_HOME}/bin:$PATH
echo $LANG
export LANG=zh_CN.UTF-8
WORKSPACE_HOME=/biz/web/site/
PROJECT_WORKSPACE=${WORKSPACE_HOME}/task.i532.net
jar_file=${PROJECT_WORKSPACE}/task-1.0-SNAPSHOT.jar

app_port=10007

jvm_xms=800M
jvm_xmx=800M
jvm_metasize=150M
jvm_maxmeta=300M
jvm_directmem=256M

TMP_DIR=/biz/web/site/temp

JVM_OPTS="-Xms${jvm_xms} -Xmx${jvm_xmx} -XX:MetaspaceSize=${jvm_metasize} -XX:MaxMetaspaceSize=${jvm_maxmeta} -XX:SurvivorRatio=8 -XX:NewRatio=2 -Xss256K -XX:+UseParallelGC -XX:+UseParallelOldGC -XX:MaxDirectMemorySize=${jvm_directmem} -Djava.io.tmpdir=$TMP_DIR"
JVM_GC_PARAMS="-XX:+PrintTenuringDistribution -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime"

arguments=(-Dsun.misc.URLClassPath.disableJarChecking=true ${JVM_OPTS} -jar "$jar_file" --spring.profiles.active=prod --server.port=${app_port} --db.configlocation=/biz/web/site/dbconf/prod/dbconfig.json  "$@")

status(){
  pid=$(lsof -i:${app_port}|awk 'NR>1 {print $2}')
  if echo "${pid}"
  then
    echo "process is running";return 0;
  else
    echo "process not running";
    return 1
  fi
}

start(){
  java "${arguments[@]}" >/biz/web/site/task.i532.net/nohup.log 2>&1 &
  echo $! > /biz/web/site/task.i532.net/task.pid
  sleep 5s
  pid=$(cat /biz/web/site/task.i532.net/task.pid)
  if echo "$pid"
  then
    echo "process start success";return 0;
  else
    echo "process start fail";
    return 1
  fi
}

stop(){
  pid=$(cat /biz/web/site/task.i532.net/task.pid)
  echo "pid:${pid}";
  kill -15 $pid && { echo "stopped [$pid]";  return 0;}
  echo "Unable to kill process $1";
  return 1;
}

update(){
  stop
  rm -rf /biz/web/site/task.i532.net/task-1.0-SNAPSHOT.jar
  mv /biz/web/site/task.i532.net/temp/task-1.0-SNAPSHOT.jar /biz/web/site/task.i532.net/task-1.0-SNAPSHOT.jar
  start;
}

action="$1"
case "$action" in
start)
  start "$@"; exit $?;;
stop)
  stop "$@"; exit $?;;
status)
  status "$@"; exit $?;;
update)
  update "$@"; exit $?;;
*)
  echo "Usage: $0 {start|stop|status|update}"; exit 1;
esac

exit 0

编写部署代码

引入maven

<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>2.9.2</version>
</dependency>
<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>2.9.2</version>
</dependency>
<dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
     <version>5.8.0.M2</version>
</dependency>

编写代码

@Api(tags = {"系统部署-测试环境"})
@RestController
@RequestMapping("/deploytest")
public class DeployTestController {
    Logger logger = LoggerFactory.getLogger(DeployTestController.class);
    @Value("${com.slwx.uploadtemp}")
    String tempdir;

    @ApiOperation("定时任务-后台")
    @PostMapping("tasktest")
    public BaseResult deployTaskTest(@RequestParam(value = "file") MultipartFile file) throws Exception{
        String dir = "/biz/web/site/task.test.i532.net/temp/";
        String filename = "task-1.0-SNAPSHOT.jar";
        if(!filename.equals(file.getOriginalFilename())){
            return BaseResult.fail("失败,文件名不正确");
        }
        FileUtil.transTo(file,dir,filename);
        //打包执行命令
        RuntimeUtil.exec("/bin/sh", "-c", "cd /etc/init.d;./testtask update");
        return BaseResult.succ("成功");
    }

}

说明:RuntimeUtil是hutool自带的工具类,"/bin/sh -c"用于linux使用字符串的方式执行命令,否则权限不允许直接执行,将一直返回错误信息。

nginx配置

upstream appapi_xxx_com {
    server 127.0.0.1:10006 weight=3 max_fails=2 fail_timeout=30s;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name appapi.i532.net;

    ssl_certificate "/usr/local/nginx/conf/xxx__xxxx.com.pem";
    ssl_certificate_key "/usr/local/nginx/conf/xxx__xxx.com.key";

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout 10m;

    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_prefer_server_ciphers on;

    add_header Content-Security-Policy "upgrade-insecure-requests;connect-src *";

    location / {
        proxy_pass http://appapi_xxx_com;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        break;
    }
}