基于 kubernetes 平台微服务的部署

基于 kubernetes 平台微服务的部署

系统管理 --> 创建管理

系统管理 --> Manage Credential --> 全局 --> 添加凭证

点击确定后,选择 k8s-auth,点击更新

//脚本更新后如下:

修改 k8s_auth 的 id, 红色部分复制即可

def git_address = "http://192.168.10.10:82/xxx_group/tensquare_back.git" 
def git_auth = "fc0fab00-287d-4803-aba2-42ee7714028a"
//构建版本的名称
def tag = "latest"
//Harbor私服地址
def harbor_url = "192.168.10.60:85"
//Harbor的项目名称
def harbor_project_name = "tensquare"
//Harbor的凭证
def harbor_auth = "4a3d4e32-fc80-472c-8ca9-b942ceb6ac4a"
//k8s的凭证
def k8s_auth="4c644388-ffa4-443c-a891-68c60a082db2"
//定义k8s-barbor的凭证
def secret_name="registry-auth-secret"


podTemplate(label: 'jenkins-slave', cloud: 'kubernetes', containers: [ 
        containerTemplate(
            name: 'jnlp',
            image: "192.168.10.60:85/library/jenkins-slave-maven:latest"
        ),
        containerTemplate( 
            name: 'docker',
            image: "docker:stable",
            ttyEnabled: true,
            command: 'cat'
        ),
    ],
    volumes: [
        hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
        nfsVolume(mountPath: '/usr/local/apache-maven/repo', serverAddress: '192.168.10.90' , serverPath: '/opt/nfs/maven'),
    ],
)
{
node("jenkins-slave"){
    // 第一步
    stage('pull code'){
        checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]])
    }
    // 第二步
    stage('make public sub project'){
        //编译并安装公共工程
        sh "mvn -f tensquare_common clean install"
    }
    // 第三步
    stage('make image'){
        //把选择的项目信息转为数组
        def selectedProjects = "${project_name}".split(',')


        for(int i=0;i<selectedProjects.size();i++){
            //取出每个项目的名称和端口
            def currentProject = selectedProjects[i];
            //项目名称
            def currentProjectName = currentProject.split('@')[0]
            //项目启动端口
            def currentProjectPort = currentProject.split('@')[1]

            //定义镜像名称
            def imageName = "${currentProjectName}:${tag}"

            //编译,构建本地镜像
            sh "mvn -f ${currentProjectName} clean package dockerfile:build"
            container('docker') {

                //给镜像打标签
                sh "docker tag ${imageName} ${harbor_url}/${harbor_project_name}/${imageName}"

                //登录Harbor,并上传镜像
                withCredentials([usernamePassword(credentialsId: "${harbor_auth}", passwordVariable: 'password', usernameVariable: 'username')])
                {
                    //登录
                    sh "docker login -u ${username} -p ${password} ${harbor_url}"
                    //上传镜像
                    sh "docker push ${harbor_url}/${harbor_project_name}/${imageName}"
                }                      

            //删除本地镜像
            sh "docker rmi -f ${imageName}" 
            sh "docker rmi -f ${harbor_url}/${harbor_project_name}/${imageName}"
            }
            def deploy_image_name = "${harbor_url}/${harbor_project_name}/${imageName}"
            //部署到K8S 
            sh """
                sed -i 's#\$IMAGE_NAME#${deploy_image_name}#' ${currentProjectName}/deploy.yml
                sed -i 's#\$SECRET_NAME#${secret_name}#' ${currentProjectName}/deploy.yml
            """
            kubernetesDeploy configs: "${currentProjectName}/deploy.yml", kubeconfigId: "${k8s_auth}"
        }
    }
}
}

把上面脚本粘贴到项目中

项目 tensquare_back --> 配置

1、部署注册中心 Eureka

//创建 deploy.yml

//deploy.yml 内容如下

---
apiVersion: v1
kind: Service
metadata:
  name: eureka
  labels:
    app: eureka
spec:
  type: NodePort
  ports:
    - port: 10086
      name: eureka
      targetPort: 10086
  selector:
    app: eureka
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: eureka
spec:
  serviceName: "eureka"
  replicas: 2
  selector:
    matchLabels:
      app: eureka
  template:
    metadata:
      labels:
        app: eureka
    spec:
      imagePullSecrets:
        - name: $SECRET_NAME
      containers:
        - name: eureka
          image: $IMAGE_NAME
          ports:
            - containerPort: 10086
          env:
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: EUREKA_SERVER
              value: "http://eureka-0.eureka:10086/eureka/,http://eureka- 1.eureka:10086/eureka/"
            - name: EUREKA_INSTANCE_HOSTNAME
              value: ${MY_POD_NAME}.eureka
  podManagementPolicy: "Parallel"

//application.yml 配置文件更改如下(之前内容删除,以下脚本粘贴进去)

server:
  port: ${PORT:10086}
spring:
  application:
    name: eureka

eureka:
  server:
    # 续期时间,即扫描失效服务的间隔时间(缺省为60*1000ms)
    eviction-interval-timer-in-ms: 5000
    enable-self-preservation: false
    use-read-only-response-cache: false
  client:
    # eureka client间隔多久去拉取服务注册信息 默认30s
    registry-fetch-interval-seconds: 5
    serviceUrl:
      defaultZone: ${EUREKA_SERVER:http://127.0.0.1:${server.port}/eureka/}
  instance:
    # 心跳间隔时间,即发送一次心跳之后,多久在发起下一次(缺省为30s)
    lease-renewal-interval-in-seconds: 5
    #  在收到一次心跳之后,等待下一次心跳的空档时间,大于心跳间隔即可,即服务续约到期时间(缺省为90s)
    lease-expiration-duration-in-seconds: 10
    instance-id: ${EUREKA_INSTANCE_HOSTNAME:${spring.application.name}}:${server.port}@${random.l ong(1000000,9999999)}
    hostname: ${EUREKA_INSTANCE_HOSTNAME:${spring.application.name}}

提交、推送整个Eureka项目

构建前,由于 k8s 访问 harbor 需要密钥权限

//在k8s所有主机上操作
docker login -u tom -p Abcd1234 192.168.10.60:85

//在master 上操作即可 kubectl create secret docker-registry registry-auth-secret --docker-server=192.168.10.60:85 --docker-username=tom --docker-password=Abcd1234 -- docker-email=tom@qq.com

开始构建

构建成功

访问两个 node 节点的 32169 端口(node的ip+端口)

2、部署服务网关 zuul

更改配置文件 application.yml中的 eureka 集群地址

红色部分做修改

server:
  port: 10020 # 端口
  
# 基本服务信息
spring:
  application:
    name: tensquare-zuul # 服务ID
    
# Eureka配置
eureka:
  client:
    service-url:  
      defaultZone: http://eureka-0.eureka:10086/eureka/,http://eureka- 1.eureka:10086/eureka/ # Eureka访问地址
  instance:
    prefer-ip-address: true
  
# 修改ribbon的超时时间
ribbon:
  ConnectTimeout: 1500 # 连接超时时间,默认500ms
  ReadTimeout: 3000  # 请求超时时间,默认1000ms
  
  
# 修改hystrix的熔断超时时间
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMillisecond: 2000 # 熔断超时时长,默认1000ms
            

# 网关路由配置
zuul:
  routes:
    admin:
      path: /admin/**
      serviceId: tensquare-admin-service
    gathering:
          path: /gathering/**
          serviceId: tensquare-gathering

 # jwt参数
jwt:
  config:
    key: itcast
    ttl: 1800000

zuul下面 创建配置文件 deploy.yml 如下其他项目名字和端口进行修改即可)

---
apiVersion: v1
kind: Service
metadata:
  name: zuul
  labels:
    app: zuul
spec:
  type: NodePort
  ports:
    - port: 10020
      name: zuul
      targetPort: 10020
  selector:
    app: zuul
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: zuul
spec:
  serviceName: "zuul"
  replicas: 2
  selector:
    matchLabels:
      app: zuul
  template:
    metadata:
      labels:
        app: zuul
    spec:
      imagePullSecrets:
        - name: $SECRET_NAME
      containers:
        - name: zuul
          image: $IMAGE_NAME
          ports:
            - containerPort: 10020
  podManagementPolicy: "Parallel"

手动上传父工程依赖到 NFS Maven 共享仓库目录中

上传 、推送整个 zuul项目

开始构建

构建成功

3、部署认证中心 admin_service

更改配置文件 application.yml中的 eureka 集群地址

server:
  port: 9000
spring:
  application:
    name: tensquare-admin-service #指定服务名
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.10.20:3306/tensquare_user?characterEncoding=UTF8
    username: root
    password: abc123
  jpa:
    database: mysql
    show-sql: true

#Eureka配置
eureka:
  client:
    service-url:
      defaultZone: http://eureka-0.eureka:10086/eureka/,http://eureka- 1.eureka:10086/eureka/
  instance:
    lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
    lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
    prefer-ip-address: true


  # jwt参数
jwt:
  config:
    key: itcast
    ttl: 1800000

创建deploy.yml 文件(修改服务名称和端口)

---
apiVersion: v1
kind: Service
metadata:
  name: admin
  labels:
    app: admin
spec:
  type: NodePort
  ports:
    - port: 9000
      name: admin
      targetPort: 9000
  selector:
    app: admin
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: admin
spec:
  serviceName: "admin"
  replicas: 2
  selector:
    matchLabels:
      app: admin
  template:
    metadata:
      labels:
        app: admin
    spec:
      imagePullSecrets:
        - name: $SECRET_NAME
      containers:
        - name: admin
          image: $IMAGE_NAME
          ports:
            - containerPort: 9000
  podManagementPolicy: "Parallel"

提交代码、推送,直接构建

4、部署活动微服务 gathering

更改配置文件 application.yml中的 eureka 集群地址

server: 
  port: 9002
spring: 
  application:  
    name: tensquare-gathering #指定服务名
  datasource:  
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.10.20:3306/tensquare_gathering?characterEncoding=UTF8
    username: root
    password: abc123
  jpa: 
    database: mysql
    show-sql: true
#Eureka客户端配置
eureka:
  client:
    service-url:
      defaultZone: http://eureka-0.eureka:10086/eureka/,http://eureka- 1.eureka:10086/eureka/
  instance:
    lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
    lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
    prefer-ip-address: true

创建 deploy.yml 配置如下

---
apiVersion: v1
kind: Service
metadata:
  name: gathering
  labels:
    app: gathering
spec:
  type: NodePort
  ports:
    - port: 9002
      name: gathering
      targetPort: 9002
  selector:
    app: gathering
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: gathering
spec:
  serviceName: "gathering"
  replicas: 2
  selector:
    matchLabels:
      app: gathering
  template:
    metadata:
      labels:
        app: gathering
    spec:
      imagePullSecrets:
        - name: $SECRET_NAME
      containers:
        - name: gathering
          image: $IMAGE_NAME
          ports:
            - containerPort: 9002
  podManagementPolicy: "Parallel"

提交代码、推送,直接构建

5、使用 postman 直接连接数据库查询获取后台数据

 

登录 mysql 数据库(装在Jenkins服务器192.168.10.20上)

账户密码:root/abc123

 

 

访问使用 nodeIP :30904 来访问服务网关

http://192.168.10.100:30904/admin/admin/login

http://192.168.10.100:30904/gathering/gathering

 

posted @ 2022-03-12 01:05  DoYouWantMore  阅读(313)  评论(0编辑  收藏  举报