1. 安装jenkins的yum源
```
sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
```
2. 安装验证源的key
```
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
```
3. 安装jenkins
```
yum install jenkins -y
``` 
4. 根据指引操作，到服务器上获取token，输入。等等
5. 安装所需要的插件
    - Active Choices Plug-in
    - Ansible plugin
    - Ant Plugin
    - Blue Ocean*(凡是有Blue Ocean的全都选择)
    - Git
    - Pipeline（凡是有Pipeline的全都选择）
    - Publish Over SSH
6. 配置job。具体jenkins job请询问已部署过jenkins的项目（crm，定价）。

# commons
创建一个maven项目
![avatar](./images/commons.png)
![avatar](./images/commons2.png)
输入git地址
![avatar](./images/commons3.png)
运行打包命令
# mayi-service（根据项目按需改动）
创建一个pipeline项目
![avatar](./images/service1.png)
![avatar](./images/service2.png)
![avatar](./images/service3.png)
设置选项参数
![avatar](./images/service4.png)
![avatar](./images/service45.png)
![avatar](./images/service5.png)
修改如下脚本
```
pipeline {
  agent any
  
  parameters {
    booleanParam defaultValue: true, description: '自动重启', name: 'autoRestart'
    booleanParam defaultValue: true, description: '编译其他 ', name: 'buildDep'
    choice choices: ['kuka_crm_uat','kuka_crm_online'], description: '', name: 'env' #选项参数 选择两个环境
    gitParameter branchFilter: 'origin/(.*)', defaultValue: 'crm-dev', name: 'BRANCH', selectedValue: 'DEFAULT',type: 'PT_BRANCH' #选择git分支
  }
  // 配置项
  options {
    //timestamps
    // 保留最后7个构件记录
    buildDiscarder(logRotator(numToKeepStr: '7'))
    // 不允许并行执行Pipeline,可用于防止同时访问共享资源等
    disableConcurrentBuilds()
  }
  stages {
    // 编译阶段
    stage('SCM') {
      steps {
        checkout([$class: 'GitSCM', branches: [[name: '*/crm-dev']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '4a5d05d2-97e2-47e2-802b-e6d57aba31ec', url: 'http://code.mayi888.com/mayi888/mayi-service.git']]])# git 地址 通过左边Pipeline Syntax这个按钮选择scm单元生成
      }
    }
    // 发布阶段
    stage('build dependencies proj') {
      when {
        expression { params.buildDep }
      }
      steps {
          withMaven(maven: 'maven', mavenSettingsFilePath: '/opt/apache-maven-3.5.4/conf/settings.xml')#maven地址 {
            build(job: 'commons')
          }
      }
    }
    // 编译阶段
    stage('Build') {
      steps {
          withMaven(maven: 'maven', mavenSettingsFilePath: '/opt/apache-maven-3.5.4/conf/settings.xml') {
            sh 'java -version'
            sh 'mvn clean'
            // build(job: 'pos', parameters: [string(name: 'env', value: 'kuka_test'),string(name: 'projects', value: '-pl mayi-pos-core-api'), gitParameter(name: 'branch', value: 'origin/kuka-qk-dev')])
            // build(job: 'commons')
            sh 'echo ${env}-${module}'
            sh 'mvn -Dmaven.test.skip=true -e  -pl ${module} -am install'
            sh 'mkdir -p servicePackages'
            sh 'cp -r -f */**/target/*.jar servicePackages 2>/dev/null || :'
            sh 'cp -r -f **/target/*.jar servicePackages 2>/dev/null || :'
            sh 'ls -l /data/servicePackages'
          }
      }
    }
    // 发布阶段
    stage('Deploy Test Env') {
      when {
        expression { params.env == 'kuka_crm_uat' }
      }
      steps {
        //to test crm
        sshPublisher(publishers: [sshPublisherDesc(configName: 'crmtest', transfers: [sshTransfer(excludes: '', execCommand: 'ls -l /data/tomcat/servicePackages', execTimeout: 0, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'servicePackages/*')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
        
      }
    }
    
    stage('Deploy online Enc'){
        when {
            expression { params.env == 'kuka_crm_online' }
        }
        steps {
            sshPublisher(publishers: [sshPublisherDesc(configName: 'crmonline1', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'ls -l /data/tomcat/servicePackages/*', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'servicePackages', remoteDirectorySDF: false, removePrefix: 'servicePackages', sourceFiles: 'servicePackages/*')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false), sshPublisherDesc(configName: 'crmonline2', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'ls -l /data/tomcat/servicePackages/*', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'servicePackages', remoteDirectorySDF: false, removePrefix: 'servicePackages', sourceFiles: 'servicePackages/*')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
        }
    }
    // 发布阶段
    stage('Restart Test Env') {
      when {
        expression { params.autoRestart }
      }
      steps {
          build job: 'test-restart-tomcat', parameters: [string(name: 'host', value: params.env=='kuka_crm_online'?'crmonline':'crmtest'), string(name: 'app', value: 'mayi-server'), string(name: 'env', value: params.env), string(name: 'model', value: params.module)]
      }
    }
  }
  // 构建后
  post {
    always {
        echo '结束'
    }
    // 成功时触发
    success{
        echo '成功'
    }

  }
}
```
# restart script(mayi-service配置后必须配置)（根据项目按需改动）
## 复制的内容
```
if (app.equals("pos")){
return [
'pos-core:selected',
'pos-manager:selected',
'pos-shop-manager:selected',
'pos-api:selected',
'pos-guide-api:selected',
'pos-open:selected'
]}
else if (app.equals("shop")){
return [
'mayi-core:selected',
'mayi-seller-manager:selected',
'mayi-shop-mobile:selected',
'mayi-seller-mobile',
'mayi-open:selected',
'mayi-manager',
'mayi-message',
'mayi-promotion-core',
'mayi-promotion-manager',
'mayi-shop-api:selected'
]}
else if(app.equals("mayi-server")){
return[
'base-service/base-service-core:selected',
'user-service/user-service-core:selected',
'order-service/order-service-core:selected',
'schedule-service/schedule-service-core:selected',
'info-service/info-service-core:selected',
'third-party-service/third-party-service-core:selected',
'customer-service/customer-service-core:selected',
'gateway-service:selected'
]}
```
```
#!/bin/bash
BUILD_ID=notkill


echo '#!/bin/bash
echo "*************************************************"
#echo $1
#s=$1
servers=(${1//,/ })
tomcatHome=/data/tomcat

tomcatNames=(
mayi-core
mayi-manager
mayi-shop-mobile
mayi-seller-mobile
mayi-seller-manager
mayi-print
mayi-message
mayi-open
mayi-promotion-core
mayi-promotion-manager
mayi-shop-api
pos-core
pos-manager
pos-open
pos-shop-manager
pos-api
pos-guide-api
)
tomcatDirectorys=(
$tomcatHome/apache-tomcat-7.0.57-mayi-core
$tomcatHome/apache-tomcat-7.0.57-mayi-manager
$tomcatHome/apache-tomcat-7.0.57-mayi-shop-mobile/
$tomcatHome/apache-tomcat-7.0.57-mayi-seller-mobile
$tomcatHome/apache-tomcat-7.0.57-mayi-seller-manager
$tomcatHome/apache-tomcat-7.0.57-mayi-print/
$tomcatHome/apache-tomcat-7.0.57-mayi-message/
$tomcatHome/apache-tomcat-7.0.57-mayi-open/
$tomcatHome/apache-tomcat-7.0.57-mayi-promotion-core/
$tomcatHome/apache-tomcat-7.0.57-mayi-promotion-manager/
$tomcatHome/apache-tomcat-8.0.52-mayi-shop-api/
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-core
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-manager
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-open
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-shop-manager
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-api
$tomcatHome/apache-tomcat-7.0.57-mayi-pos-guide-api
)
pros=(
mayi-core
ROOT
ROOT
ROOT
ROOT
ROOT
ROOT
ROOT
ROOT
mayi-promotion-manager
ROOT
mayi-pos-core
ROOT
ROOT
ROOT
ROOT
ROOT
)
urls=(
http://127.0.0.1:8180/mayi-core/
http://127.0.0.1:8280/login.htm
http://127.0.0.1:8380/login.htm
http://127.0.0.1:8480/login.htm
http://127.0.0.1:8580/login.htm
http://127.0.0.1:8680/
http://127.0.0.1:8780
http://127.0.0.1:8880/doc
http://127.0.0.1:8980/
http://127.0.0.1:9080/mayi-promotion-manager/
http://127.0.0.1:18980/swagger-ui.html
http://127.0.0.1:19080/mayi-pos-core/
http://127.0.0.1:9180
http://127.0.0.1:9580/sample/sample.htm
http://127.0.0.1:9280
http://127.0.0.1:9380/sample/sample.htm
http://127.0.0.1:9480/sample/sample.htm
)
warFileNames=(
$tomcatHome/shopwars/mayi-core.war
$tomcatHome/shopwars/ROOTMayiManager.war
$tomcatHome/shopwars/ROOTSHOPM.war
$tomcatHome/shopwars/ROOTSellerM.war
$tomcatHome/shopwars/ROOTSellerManager.war
$tomcatHome/shopwars/ROOTMayiPrint.war
$tomcatHome/shopwars/ROOTMayiMessage.war
$tomcatHome/shopwars/ROOTMayiOpen.war
$tomcatHome/shopwars/mayi-promotion-core.war
$tomcatHome/shopwars/mayi-promotion-manager.war
$tomcatHome/shopwars/ROOTSHOPApi.war
$tomcatHome/poswars/mayi-pos-core.war
$tomcatHome/poswars/ROOTPosManager.war
$tomcatHome/poswars/ROOTPOSOpen.war
$tomcatHome/poswars/ROOTPosShopM.war
$tomcatHome/poswars/ROOTPOSAPI.war
$tomcatHome/poswars/ROOTPosGuide.war
)

ppp=0
for(( j=0;j<${#tomcatNames[@]};j++))
do
    tomcatName=${tomcatNames[j]}
    for(( k=0;k<${#servers[@]};k++))
    do
    	s=${servers[k]}
        if [ $tomcatName = $s ];then
		    ppp=$[ppp+1]
            pro=${pros[j]}
            url=${urls[j]}
            #port=${ports[j]}
            warFileName=${warFileNames[j]}
            tomcatDirectory=${tomcatDirectorys[j]}
    
            echo url: $url
            echo tomcatName: $tomcatName
            echo tomcatDirectory: $tomcatDirectory
            echo warFileName: $warFileName
    
            if [ -d $tomcatDirectoy ];then
                cd $tomcatDirectory
                ##监控项目是否在运行
                httpCode=$(curl -s -o /dev/null -m 10 --connect-timeout 10 $url -w %{http_code})
                echo 监控Tomcat是否正在运行 httpCode: $httpCode
                ##如果在运行就停止  -eq 200
                if [ $httpCode -ne 502 ];then
                    data=`ps -ef|grep $tomcatName/bin |grep -v $0 |grep -v '\'grep\'' `;
                    echo "$data";
                    pid=`ps -ef|grep $tomcatName/bin |grep -v $0 |grep -v '\'grep\'' | awk '\'{print \$2}\''`;
                    echo "PID: $pid";
                    echo "开始停止 $tomcatName";
    
                    # if [ -n "$pid" ];then
                    #     kill -9 $pid;
                    #     sleep 3;
                    # fi
                    while [ -n "$pid" ]
                    do
                        kill -9 $pid;
                        sleep 3;
                        pid=`ps -ef|grep $tomcatName |grep -v $0 |grep -v '\'grep\'' | awk '\'{print \$2}\''`;
                    done
                    echo "停止 $tomcatName 成功"
                fi
    
                # pid=`lsof -i:$port |awk 'NR==2{print $2}'`;
                # if [ -n "$pid" ];then
                #     echo "开始停止 $tomcatName";
                #     while [ -n "$pid" ]
                #     do
                #         kill -9 $pid;
                #         sleep 3;
                #       pid=`lsof -i:$port |awk 'NR==2{print $2}'`;
                #     done
                #     echo "停止 $tomcatName 成功"
                # fi
                ##判断是否存在war包 有则备份原来的war包  并把新war移动到webapp目录下
                if [ -f "${warFileName}" ];then
                    echo 文件 ${warFileName} 存在  准备启动Tomcat
    
                    oldFile=./webapps/${pro}.war
                    echo $oldFile
                    updateDate=`stat -c %y $oldFile | awk '\'{print \$1\$2}\''`
                    echo $updateDate
                    #把上一次发布的包给重命名
##                    mv $oldFile $oldFile'.old'
                    ##删除解压出来的目录
                    rm -rf ./webapps/${pro}
                    #把新包放到webapps目录下
                    cp -rf ${warFileName} $oldFile
                fi
                ##删除日志文件
                ##echo 删除日志
                rm -rf logs/*
    
                echo "开始启动 $tomcatName"
                ./bin/startup.sh
                httpCode=502
                i=0
                ##监控Tomcat是否启动成功
                
                while ([ $httpCode -ne 200 ] && [ $i -le 50 ])
                do
                    sleep 1
                    httpCode=$(curl -s -o /dev/null -m 10 --connect-timeout 10 $url -w %{http_code})
                    i=`expr $i + 1`
                    echo ${i} 监控Tomcat是否启动成功 httpCode: $httpCode
                done
                if [ $httpCode -eq 200 ];then
                    echo "启动 $tomcatName 成功"
                else
                    echo "启动 $tomcatName 失败"
                fi
                echo "***********************"$ppp"/"${#servers[@]}"**************************"
            else
                echo tomcat目录不正确
                echo "***********************"$ppp"/"${#servers[@]}"**************************"
                exit 0;
            fi
        fi
    done;
done;
env=$2

echo "**************** spring boot 项目 **************"

jmxports=(
60001
60002
60003
60004
60005
60006
60007
60008
60009
60010
)
springServices=(
user-service
base-service
order-service
schedule-service
info-service
integral-service
third-party-service
gateway-service
customer-service
activiti-service
)

for(( j=0;j<${#springServices[@]};j++))
do
    springSrv=${springServices[j]}
    jmxport=${jmxports[j]}
    hostname=`echo $HOSTNAME`
    A="crmtest"
    
    echo "输入的原始值：A=$A,B=$hostname"
    
    #判断字符串是否相等
    if [ "crmtest" = "$hostname" ];then
    ip="172.16.233.20"
    echo "$ip"
    fi
    if [ "crmonline1" = "$hostname" ];then
    ip="172.16.233.19"
    echo "$ip"
    fi
    if [ "crmonline2" = "$hostname" ];then
    ip="172.16.233.18"
    echo "$ip"
    fi
    echo "springSrv : $springSrv"
    for(( k=0;k<${#servers[@]};k++))
    do
        ppp=$[k+1]
        s=${servers[k]}
        echo "比较 名称$springSrv : $s"
        if echo $s |grep $springSrv;then
          echo "---------------$springSrv start------------------";
          data=`ps -ef|grep $springSrv | grep $env |grep -v $0 |grep -v grep`
          echo "$data";
          pid=`ps -ef|grep $springSrv | grep $env |grep -v $0 |grep -v grep | awk '\'{print \$2}\''`
          echo "PID: $pid";
          echo "开始停止 ${springSrv}";

          while [ -n "$pid" ]
          do
            kill -9 $pid;
            sleep 3;
            pid=`ps -ef|grep $springSrv | grep $env |grep -v $0 |grep -v grep | awk '\'{print \$2}\''`
          done
          echo "停止 ${springSrv} 成功"

          mkdir -p $tomcatHome/test-${springSrv}
          cd $tomcatHome/test-${springSrv}
          logFile=${springSrv}.log
          jarFile=${springSrv}-core*.jar
          newJarFile=$tomcatHome/servicePackages/$jarFile
          if [ -f $newJarFile ]; then
          	if [ -f $jarFile ]; then
            	echo "备份旧的jar"
          		mv $jarFile ${jarFile}.bak
            fi
            echo "删除log"
          	rm -rf logs $logFile
            echo "复制jar"
	        mv $newJarFile ./
            echo "启动服务"
          fi
         for i in $springServices;
         do
         nohup java -Xms512m -Xmx512m -Djava.rmi.server.hostname=${ip} -Dcom.sun.management.jmxremote  -Dcom.sun.management.jmxremote.port=${jmxport} -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.security.egd=file:/dev/./urandom -jar   ${springSrv}-core*.jar --spring.profiles.active=${env}  > $logFile 2>&1 &
         sleep 45
         done
          echo "---------------$springSrv end------------------"; 
        fi
    done;
done;
' > restart-tomcat.sh
```

创建一个自由风格项目
![avatar](./images/restart1.png)
![avatar](./images/restart2.png)
![avatar](./images/restart3.png)
![avatar](./images/restart4.png)