Use Coding to automate the deployment of java projects (useful for personal testing)

Article directory

What is Coding? Take a look at Baidu Encyclopedia
https://baike.baidu.com/item/coding/8921246?fr=aladdin

Comparison between ordinary deployment and automated deployment
Ordinary deployment: open the jar package -> upload the jar package to the server -> execute the java -jar command, it seems that it is not very troublesome...

Coding automated deployment: Submit code -> trigger build, start automated deployment, is it very convenient and fast?

The demonstration here is to automatically deploy the springboot project to the pagoda server

Coding automated deployment

1. First, create a project:

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Then click Finish to create

Click here to upload the project

insert image description here
Just choose the first template.

After the creation is successful, just build a Spring Boot project and upload it to the code warehouse of the project.

2. Start configuration build

2.1 Click Continuous Integrationinsert image description here

2.2 Click to create a build plan

insert image description here

2.3 Select java this

insert image description here

2.5 Configure the following according to my circle

insert image description here

2.6 If these few are not newly created, you can use docker here

insert image description here

The compilation and construction of the maven project can use this

mvn clean install

insert image description here

2.7 This is to be newly created

insert image description here

insert image description here

Write server address to enable deployment to remote server

insert image description here

It is important to create new ssh login credentials

insert image description here
insert image description here

The SSH private key* acquisition method is demonstrated here for the pagoda server, and the others are similar

Enter ssh-keygen -m PEM -t rsa in the Pagoda terminal and press Enter

insert image description here

SSH private key* Put this SSH private key* in this file and save it here

/root/.ssh/id_rsa.

insert image description here

There is also the ssh public key to configure the public key in the pagoda in this file

/root/.ssh/id_rsa.pub.

Copy the content of the generated public key (id_rsa.pub.) and put it into (accessed) server root/.ssh/authorized_keys Paste it into this file to indicate authorization; other servers can access this server through the private key without this file or folder to create one;

insert image description here

It is recommended to directly authorize here and click to confirm

insert image description here

After creation, copy this credential id and save it for use below

insert image description here

Remember to choose the code repository you created

insert image description here

Click here to confirm

insert image description here

After clicking OK, it will jump to the process configuration, click the text editor, and overwrite the original content with the following content:

What needs to be covered is what's here

insert image description here

Paste the code below into the image above

pipeline {
    
    
  agent any
  stages {
    
    
    stage('检出') {
    
    
      steps {
    
    
        checkout([
          $class: 'GitSCM',
          branches: [[name: env.GIT_BUILD_REF]],
          userRemoteConfigs: [[
            url: env.GIT_REPO_URL,
            credentialsId: env.CREDENTIALS_ID
          ]]])
        }
      }
      stage('构建${packageType}') {
    
    
        steps {
    
    
          echo '构建中...'
          sh 'mvn clean package -Ptest -DskipTests'
          echo '构建完成.'
        }
      }
      stage('收集构建物') {
    
    
        steps {
    
    
          archiveArtifacts 'target/*.jar'
        }
      }
      stage('部署到服务器') {
    
    
        steps {
    
    
          script {
    
    
            def remote = [:]
            remote.name = 'zqh'
            remote.host = '自己服务器ip地址'
            remote.user = 'root'
            remote.allowAnyHosts = true
            withCredentials([sshUserPrivateKey(credentialsId: "刚才复制的凭据id", keyFileVariable: 'id_rsa')]) {
    
    
              remote.identityFile = id_rsa
              stage("推送文件到远程服务器") {
    
    
                sshPut remote: remote, from: 'target/jshERP.jar', into: '/coding/zqh/'
              }
              stage("重启服务") {
    
    
                $result = sshCommand remote: remote, command: 'sh /coding/zqh/spring-start.sh restart /coding/zqh/jshERP.jar 7003'
                if($result.indexOf("jar包启动超时-1") > -1){
    
    
                  echo 'jar包启动超时-1'
                  set -e
                }
              }
            }
          }

        }
      }
    }
  }

The above code has places to modify and precautions

1. Make sure that the pagoda server has these two folders /coding/zqh, both of which need to be newly created. After the new creation is completed, you must authorize it, otherwise an error will be reported if the jar cannot be uploaded

insert image description here

authorized

insert image description here

2. Fill in your own server ip

3. One is to fill in the credential id, which was automatically created for us when we created the build plan just now, just copy the credential id (the picture below is the location of the credential id):

insert image description here
insert image description here

At this point the configuration is over.

3. Be sure to configure

A spring-start.sh script is needed, just copy the script to the /coding/zqh/ directory of the server. Pay attention to whether the jdk directory is correct and whether the directory where the jar package is located is correct.

#!/bin/bash
JVM_OPEION='-Xms246m -Xmx246m'
JAR_PID='无效'
# jar包所在的目录
JAR_HOME='/opt/zqh/'
# JDK的目录
JAVA_HOME='/usr/local/btjdk/jdk8/bin/java'
JAR_ACTIVE='prod'
# 检查次数
EXAMINE_TIME=50
#使用说明,用来提示输入参数
usage() {
    
    
  echo "Usage: sh spring-startup.sh [start|stop|restart|status]"
  exit 1
}

#检查程序是否在运行
is_exist() {
    
    
  orderStr="ps -ef | grep $1 | grep -v "\$0" | grep -v "grep" | awk '{print \$2}'"
  echo "检查命令: $orderStr"
  pid=$(eval $orderStr)
  #如果存在返回1,不存在返回0
  if [ -n "${pid}" ]; then
    JAR_PID=$pid
    echo "pid=${pid}"
    echo "JAR_PID=${JAR_PID}"
    return 1
  else
    return 0
  fi
}

#启动方法
start() {
    
    
  is_exist $1
  if [ $? -eq "1" ]; then
    echo "$1 is already running. pid=${JAR_PID} ."
  else
    echo "--------$1 开始启动--------"
    jarname=$1
    filename=${
    
    jarname##*/}
    name=${
    
    filename%.*}
    logName=${
    
    name%_*}_$2.log
    javaShellStr="nohup $JAVA_HOME -jar $1 --spring.profiles.active=$JAR_ACTIVE --server.port=$2 >/opt/api-server/logs/$logName 2>&1 &"
    echo "启动命令: $javaShellStr"
    eval $javaShellStr
    # 检查端口
    portStr="lsof -i:$2 | grep "LISTEN" | awk '{print \$2}'"
    echo "端口检查:$portStr"
    jarPort=$(eval $portStr)
    # 计时器
    stime=0
    # 判断端口是否为0,次数是否小于7
    until [[ -n "$jarPort" ]]; do
      sleep 3s
      tail -n 5 $JAR_HOME/logs/$logName
      stime=$((stime + 1))
      jarPort=$(eval $portStr)
      echo "启动检查第$stime次"
      # 超时判断 大于13,打印 -1 结束当前操作
      if [ $stime -ge $EXAMINE_TIME ]; then break; fi
    done
    if [ $stime -ge $EXAMINE_TIME ]; then
      echo "jar包启动超时-1"
      exit; fi
    echo "$1 start success"
  fi
}

#停止方法
stopPort() {
    
    
  portStr="netstat -nlp | grep :$1 | awk '{print \$7}' | awk -F\"/\" '{ print \$1 }'"
  echo "启动命令: $portStr"
  JAR_PID=$(eval $portStr)
  if [ -n "$JAR_PID" ]; then
    kill -9 $JAR_PID
    JAR_PID=$(eval $portStr)
    if [ -n "$JAR_PID" ]; then
      echo "$1 is running. Pid is ${JAR_PID}"
    else
      echo "$1 is stop."
    fi
  else
    echo "$1 is not running"
  fi
}

#停止方法
stop() {
    
    
  is_exist $1
  if [ $? -eq "1" ]; then
    while [[ -n "$JAR_PID" && "$JAR_PID" -ne "0" ]]; do
      echo "$1 is already running. pid=${JAR_PID} ."
      kill -9 $JAR_PID
      sleep 1s
      is_exist $1
      JAR_PID=$?
    done
    echo "$1 is kill"
  else
    echo "$1 is not running"
  fi
}

#输出运行状态
status() {
    
    
  is_exist $1
  if [ $? -eq "1" ]; then
    echo "$1 is running. Pid is ${JAR_PID}"
  else
    echo "$1 is NOT running."
  fi
}

#重启
restart() {
    
    
  stop $1
  start $1 $2
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
  start $2 $3
  ;;
"stop")
  stop $2
  ;;
"status")
  status $2
  ;;
"restart")
  restart $2 $3
  ;;
*)
  usage
  ;;
esac


4. Next, we need to set up push code to build automatically

Next, we only need to change a place in the code at will in the idea, and pushing the change to our code warehouse will automatically trigger the build, and we can complete the automated deployment without doing anything.

insert image description here
insert image description here

Can be built manually

insert image description here

In addition, every time the build time is too long, you need to set a variable and cache

insert image description here
insert image description here

Checking these two will start faster next time

insert image description here

it's over here

After uploading the jar is like this

insert image description here

Guess you like

Origin blog.csdn.net/weixin_48616345/article/details/132463688