谷粒商城 - 个人笔记(集群部署篇三)

前言

  1. ​学习视频:​Java项目《谷粒商城》架构师级Java项目实战,对标阿里P6-P7,全网最强​
  2. 学习文档:

​3. 接口文档:https://easydoc.net/s/78237135/ZUqEdvA4/hKJTcbfd
4. 本内容仅用于个人学习笔记,如有侵扰,联系删

十、k8s上部署应用

1、k8s部署应用流程

在这里插入图片描述

部署应用流程:

  1. 为每一个项目准备一个Dockerfile;Docker按照这个Dockerfile将项目制作成镜像
  2. 为每一个项目生成k8s的部署描述文件
  3. Jenkins编写好Jenkinsfile

2、生产环境配置抽取

现在我们需要部署到k8s,我们需要用到的各个服务,都应该引用k8s上的服务地址

1、gulimall-auth-server
新建一个application-prod.properties配置文件

# 端口号
server.port=8080
# 应用程序名
spring.application.name=gulimall-auth-server
# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 关闭thymeleaf的缓存
spring.thymeleaf.cache=false

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# 配置SpringSession存储类型
spring.session.store-type=redis

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
# 关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

2、gulimall-cart
新建一个application-prod.properties配置文件

# 服务端口号
server.port=8080

# 应用程序名
spring.application.name=gulimall-cart

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 关闭thymeleaf的缓存
spring.thymeleaf.cache=false

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# 配置SpringSession存储类型
spring.session.store-type=redis

# 配置线程池
gulimall.thread.core= 20
gulimall.thread.max-size= 200
gulimall.thread.keep-alive-time= 10

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

3、gulimall-coupon
新建一个application-prod.properties配置文件

# 服务端口号
server.port=8080

# 应用程序名
spring.application.name=gulimall-coupon

# 数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_sms?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# mybatis-plus
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

# json的日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

# 常量
coupon.user.name=zhangsan
coupon.user.age=18

新建一个bootstrap-prod.properties配置文件

# 指定应用程序的名称
spring.application.name=gulimall-coupon

4、gulimall-gateway
新建一个application-prod.properties配置文件

# 服务端口号
server.port=8080

# 应用程序名
spring.application.name=gulimall-gateway

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

新建一个application-prod.yml配置文件

spring:
  cloud:
    gateway:
      routes:
        - id: test_route
          uri: https://www.baidu.com
          predicates:
            - Query=url,baidu

        - id: qq_route
          uri: https://www.qq.com
          predicates:
            - Query=url,qq

        - id: product_route
          uri: lb://gulimall-product
          predicates:
            - Path=/api/product/**
          filters:
            - RewritePath=/api/(?<segment>.*),/$\{segment}

        - id: third_party_route
          uri: lb://gulimall-third-party
          predicates:
            - Path=/api/thirdparty/**
          filters:
            - RewritePath=/api/thirdparty/(?<segment>.*),/$\{segment}

        - id: member_route
          uri: lb://gulimall-member
          predicates:
            - Path=/api/member/**
          filters:
            - RewritePath=/api/(?<segment>.*),/$\{segment}

        - id: order_route
          uri: lb://gulimall-order
          predicates:
            - Path=/api/order/**
          filters:
            - RewritePath=/api/(?<segment>.*),/$\{segment}

        - id: ware_route
          uri: lb://gulimall-ware
          predicates:
            - Path=/api/ware/**
          filters:
            - RewritePath=/api/(?<segment>.*),/$\{segment}

        - id: coupon_route
          uri: lb://gulimall-coupon
          predicates:
            - Path=/api/coupon/**
          filters:
            - RewritePath=/api/(?<segment>.*),/$\{segment}

        - id: admin_route
          uri: lb://gulimall-admin
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/(?<segment>.*),/gulimall-admin/$\{segment}

        - id: gulimall_host_route
          uri: lb://gulimall-product
          predicates:
            - Host=gulimall.com,item.gulimall.com

        - id: gulimall_search_route
          uri: lb://gulimall-search
          predicates:
            - Host=search.gulimall.com

        - id: gulimall_auth_route
          uri: lb://gulimall-auth-server
          predicates:
            - Host=auth.gulimall.com

        - id: gulimall_cart_route
          uri: lb://gulimall-cart
          predicates:
            - Host=cart.gulimall.com

        - id: gulimall_order_route
          uri: lb://gulimall-order
          predicates:
            - Host=order.gulimall.com

        - id: gulimall_member_route
          uri: lb://gulimall-member
          predicates:
            - Host=member.gulimall.com

        - id: gulimall_seckill_route
          uri: lb://gulimall-seckill
          predicates:
            - Host=seckill.gulimall.com

  ## 前端项目,/api
  ## http://localhost:88/api/captcha.jpg   http://localhost:8080/renren-fast/captcha.jpg
  ## http://localhost:88/api/product/category/list/tree http://localhost:10000/product/category/list/tree

5、gulimall-member
新建一个application-prod.properties配置文件

# 服务端口
server.port=8080

# 应用程序名
spring.application.name=gulimall-member

# 数据源
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_ums?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username: root
spring.datasource.password: 123456

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# 配置SpringSession存储类型
spring.session.store-type=redis

# 关闭thymeleaf的缓存
spring.thymeleaf.cache=false

# mybatis-plus
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

6、gulimall-order
新建一个application-prod.properties配置文件

# 服务端口号
server.port=8080

# 应用程序名
spring.application.name=gulimall-order

# 数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_oms?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# 配置SpringSession存储类型
spring.session.store-type=redis

# 关闭thymeleaf的缓存
spring.thymeleaf.cache=false

# springMVC的日期格式化
spring.mvc.format.date=yyyy-MM-dd HH:mm:ss

# mybatis-plus
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

# RabbitMQ
spring.rabbitmq.host=gulimall-rabbitmq-management.gulimall
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/
#开启发送端确认
#spring.rabbitmq.publisher-confirms=true #老版本配置写法
spring.rabbitmq.publisher-confirm-type=correlated
#开启发送端抵达队列确认
spring.rabbitmq.publisher-returns=true
#只要抵达队列,以异步发送优先回调我们这个returnConfirm
spring.rabbitmq.template.mandatory=true
#手动确认收货(ack)
spring.rabbitmq.listener.simple.acknowledge-mode=manual

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 线程池属性的配置
gulimall.thread.core= 20
gulimall.thread.max-size= 200
gulimall.thread.keep-alive-time= 10

# 日志
logging.level.com.atguigu=info

7、gulimall-product
新建一个application-prod.properties配置文件

# 服务端口
server.port=8080

# 应用程序名
spring.application.name=gulimall-product

# 数据源
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_pms?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username: root
spring.datasource.password: 123456

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 配置SpringSession存储类型
spring.session.store-type=redis

# 关闭thymeleaf的缓存
spring.thymeleaf.cache=false

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# spring cache
spring.cache.type=redis
#毫秒为单位
spring.cache.redis.time-to-live=3600000
#如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#spring.cache.redis.key-prefix: CACHE_
spring.cache.redis.use-key-prefix=true
#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

# json的日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

# mybatis-plus
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

# 线程池属性的配置
gulimall.thread.core=20
gulimall.thread.max-size=200
gulimall.thread.keep-alive-time=10

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

8、gulimall-search
新建一个application-prod.properties配置文件

# 服务端口
server.port=8080

# 应用程序名
spring.application.name=gulimall-search

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

#关闭thymeleaf缓存
spring.thymeleaf.cache=false

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# session存储格式
spring.session.store-type=redis

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

9、gulimall-seckill
新建一个application-prod.properties配置文件

# 服务端口
server.port=8080
# 应用程序名
spring.application.name=gulimall-seckill

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# SpringSession的存储类型
spring.session.store-type=redis

# 关闭缓存
spring.thymeleaf.cache=false

# 异步任务线程池
spring.task.execution.pool.core-size=20
spring.task.execution.pool.max-size=50

# RabbitMQ
spring.rabbitmq.host=gulimall-rabbitmq-management.gulimall
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

10、gulimall-third-party
新建一个application-prod.properties配置文件

# 服务端口
server.port=30000
# 应用程序名
spring.application.name=gulimall-third-party

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 阿里云-oss
spring.cloud.alicloud.access-key=自己的access-key
spring.cloud.alicloud.secret-key=自己的secret-key
spring.cloud.alicloud.oss.endpoint=oss-cn-shanghai.aliyuncs.com
spring.cloud.alicloud.oss.bucket=wts-gulimall

# 阿里云-短信服务
spring.cloud.alicloud.sms.host=https://fsmsn.market.alicloudapi.com
spring.cloud.alicloud.sms.path=/fsms132
spring.cloud.alicloud.sms.skin=1
spring.cloud.alicloud.sms.sign=1
spring.cloud.alicloud.sms.appcode=51d31e027**********f88ddbb4
spring.cloud.util.enabled=false


# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

11、gulimall-ware
新建一个application-prod.properties配置文件

# 服务端口
server.port=8080

# 应用程序名
spring.application.name=gulimall-ware

# 数据源
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_wms?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username: root
spring.datasource.password: 123456

# nacos注册中心
spring.cloud.nacos.discovery.server-addr=gulimall-nacos-service.gulimall:8848

# 配置redis
spring.redis.host=gulimall-redis.gulimall
spring.redis.port=6379

# json的日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

# RabbitMQ
spring.rabbitmq.host=gulimall-rabbitmq-management.gulimall
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/
#手动确认机制
spring.rabbitmq.listener.simple.acknowledge-mode=manual

# 支付宝配置
alipay.app_id=2021000116660265

# Sentinel
#Sentinel控制台地址
spring.cloud.sentinel.transport.dashboard=gulimall-sentimel-service:8333
#Sentinel传输端口
spring.cloud.sentinel.transport.port=8719
#暴露的 endpoint 路径为 /actuator/sentinel
#Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、
#当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
management.endpoints.web.exposure.include=*
#sentinel是不会对feign进行监控的,需要开启配置
feign.sentinel.enabled=true

# zipkin-链路追踪
#打开链路追踪日志
#logging.level.org.springframework.cloud.openfeign=debug
#logging.level.org.springframework.cloud.sleuth=debug
#链路追踪配置
#spring.zipkin.base-url=http://gulimall-zipkin-service.gulimall:9411/ # zipkin 服务器的地址
#关闭服务发现,否则 Spring Cloud 会把 zipkin 的 url 当做服务名称
#spring.zipkin.discoveryClientEnabled= false
#设置使用 http 的方式传输数据
#spring.zipkin.sender.type=web
#spring.zipkin.sleuth.sampler.probability= 1 # 设置抽样采集率为 100%,默认为 0.1,即 10%

# 日志
logging.level.com.atguigu=info

12、gulimall-admin
新建一个application-prod.properties配置文件

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://gulimall-mysql-master.gulimall:3306/gulimall_admin?useUnicode=true&characterEncoding=UTF-8
      username: root
      password: 123456
      initial-size: 10
      max-active: 100
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      #Oracle需要打开注释
      #validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        #login-username: admin
        #login-password: admin
      filter:
        stat:
          log-slow-sql: true
          slow-sql-millis: 1000
          merge-sql: false
        wall:
          config:
            multi-statement-allow: true

  application:
    name: gulimall-admin
  cloud:
    nacos:
      discovery:
        server-addr: gulimall-nacos-service.gulimall:8848
      config:
        import-check:
          enabled: false

##多数据源的配置
#dynamic:
#  datasource:
#    slave1:
#      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
#      url: jdbc:sqlserver://localhost:1433;DatabaseName=renren_security
#      username: sa
#      password: 123456
#    slave2:
#      driver-class-name: org.postgresql.Driver
#      url: jdbc:postgresql://localhost:5432/renren_security
#      username: renren
#      password: 123456

3、创建微服务DockerFile

3.1、Docker 深入

3.1.1、Dockerfile

在这里插入图片描述
在 Docker 中创建镜像最常用的方式,就是使用 Dockerfile。Dockerfile 是一个 Docker 镜像的描述文件,我们可以理解成火箭发射的 A、B、C、D…的步骤。Dockerfile 其内部包含了一条条的指令,每一条指令构建一层,因此每一条指令的内容,就是描述该层应当如何构建。

  1. 示例

    #基于 centos 镜像
    FROM centos
    #维护人的信息
    MAINTAINER My CentOS <534096094@qq.com>
    #安装 httpd 软件包
    RUN yum -y update
    RUN yum -y install httpd
    #开启 80 端口
    EXPOSE 80
    #复制网站首页文件至镜像中 web 站点下
    ADD index.html /var/www/html/index.html
    #复制该脚本至镜像中,并修改其权限
    ADD run.sh /run.sh
    RUN chmod 775 /run.sh
    #当启动容器时执行的脚本文件
    CMD ["/run.sh"]
    

    在这里插入图片描述
    官方文档:https://docs.docker.com/engine/reference/builder/#from
    复杂一点的示例

    #在 centos 上安装 nginx
    FROM centos
    #标明著作人的名称和邮箱
    MAINTAINER xxx xxx@qq.com
    #测试一下网络环境
    RUN ping -c 1 www.baidu.com
    #安装 nginx 必要的一些软件
    RUN yum -y install gcc make pcre-devel zlib-devel tar zlib
    #把 nginx 安装包复制到/usr/src/目录下,如果是压缩包还会自动解压,是网络路径会自动
    下载
    ADD nginx-1.15.8.tar.gz /usr/src/
    #切换到/usr/src/nginx-1.15.8 编译并且安装 nginx
    RUN cd /usr/src/nginx-1.15.8 \
    && mkdir /usr/local/nginx \
    && ./configure --prefix=/usr/local/nginx && make && make install \
    && ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ \
    && nginx
    #删除安装 nginx 安装目录
    RUN rm -rf /usr/src/nginx-nginx-1.15.8
    #对外暴露 80 端口
    EXPOSE 80
    #启动 nginx
    CMD ["nginx", "-g", "daemon off;"]
    
  2. 常用指令

    在这里插入图片描述

3.1.2、镜像操作
  1. 创建项目 dockerfile
  2. 上传项目到服务器。
  3. 进入项目,构建镜像到本地仓库;
    1. docker build -t nginx:GA-1.0 -f ./Dockerfile . 别忘了最后的小数点。
    2. docker images 查看镜像
    3. docker exec -it 容器 id /bin/bash;进入容器,修改容器
    4. docker commit -a “wts” -m “nginxxx” 容器 id mynginx:GA-2.0
      1. docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
      2. OPTIONS 说明:
        1. -a :提交的镜像作者;
        2. -c :使用 Dockerfile 指令来创建镜像;
        3. -m :提交时的说明文字;
        4. -p :在 commit 时,将容器暂停。
    5. docker login : 登陆到一个 Docker 镜像仓库,如果未指定镜像仓库地址,默认为官方仓库Docker Hub
      1. docker login -u 用户名 -p 密码
    6. docker logout : 登出一个 Docker 镜像仓库,如果未指定镜像仓库地址,默认为官方仓库 Docker Hub
  4. 推送镜像到 docker hub
    1. 标记镜像,docker tag local-image:tagname username/new-repo:tagname
    2. 上传镜像,docker push username/new-repo:tagname
  5. 保存镜像,加载镜像
    1. 可以保存镜像为 tar,使用 u 盘等设备复制到任意 docker 主机,再次加载镜像
    2. 保存:docker save spring-boot-docker -o /home/spring-boot-docker.tar
    3. 加载:docker load -i spring-boot-docker.tar
  6. 阿里云操作
    1. 登录阿里云,密码就是开通镜像仓库时 的密码
      docker login --username=qwertyuiopasdf_aa registry.cn-hangzhou.aliyuncs.com
    2. 拉取镜像
      docker pull registry.cn-hangzhou.aliyuncs.com/atguigumall/gulimall-nginx:v1.0
    3. 推送镜像
      docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/atguigumall/gulimall-nginx:v1
      docker push registry.cn-hangzhou.aliyuncs.com/atguigumall/gulimall-nginx:v1

3.2、Dcokerfile创建

1、因为容器内部的端口不会影响外部端口占用问题,所以我们把微服务的端口都统一改成8080,方便我们Dcokerfile编写。

Dcokerfile

FROM java:8
EXPOSE 8080
# 同时把微服务里的server.port改成8080
VOLUME /tmp
# 本地IDEA target/app.jar
ADD target/*.jar  /app.jar
# 主要是为了修改创建时间,可以去掉
RUN bash -c 'touch /app.jar'
# 容器启动默认运行命令,并指定配置
ENTRYPOINT ["java","-jar","/app.jar","--spring.profiles.active=prod"]

4、创建微服务k8s部署描述文件

4.1、在每个微服务下创建deploy/devops.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: 微服务名
  namespace: gulimall
  labels:
    app: 微服务名
spec:
  replicas: 1
  selector:
    matchLabels:
      app: 微服务名
  template:
    metadata:
      labels:
        app: 微服务名
    spec:
      containers:
        - name: ks
          image: $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:$TAG_NAME
          ports:
            - containerPort: 8080
              protocol: TCP
          resources:
            limits:
              cpu: 200m
              memory: 500Mi
            requests:
              cpu: 100m
              memory: 100Mi
          imagePullPolicy: IfNotPresent          
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
      restartPolicy: Always
      terminationGracePeriodSeconds: 30          
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 25%
      maxSurge: 25%
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600

---
kind: Service
apiVersion: v1
metadata:
  name: 微服务
  namespace: gulimall
  labels:
    app: 微服务
spec:
  ports:
    - name: http-8080
      protocol: TCP
      port: 8080service端口
      targetPort: 8080容器端口
      nodePort: 外部端口
  selector:
    app: 微服务
  type: NodePort
  sessionAffinity: None

示例

apiVersion: apps/v1
kind: Deployment
metadata:
  name: gulimall-auth-server
  namespace: gulimall
  labels:
    app: gulimall-auth-server
# 规格
spec:
  # 副本数
  replicas: 1
  selector:
    matchLabels:
      app: gulimall-auth-server
  template:
    metadata:
      labels:
        app: gulimall-auth-server
    spec:
      containers:
        - name: gulimall-auth-server
          image: $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:$TAG_NAME
          ports:
            - containerPort: 8080
              protocol: TCP
          resources:
            limits:
              cpu: 200m
              memory: 500Mi
            requests:
              cpu: 100m
              memory: 100Mi
          imagePullPolicy: IfNotPresent
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
    strategy:
      type: RollingUpdate
      rollingUpdate:
        maxUnavailable: 25%
        maxSurge: 25%
---
kind: Service
apiVersion: v1
metadata:
  name: gulimall-auth-server
  namespace: gulimall
  lables:
    app: gulimall-auth-server
spec:
  ports:
    - name: http-8080
      protocol: TCP
      # service端口
      port: 8080
      # 容器端口
      targetPort: 8080
      # 外部端口
      nodePort: 20002

  selector:
    app: gulimall-auth-server
  clusterIP:
  type: NodePort

4.2、 理解targetPod、Port、nodePort

devops.yaml里面的端口我们有些模糊不清,我们可以根据这张图进行分析
在这里插入图片描述

从内到外:app的port --> dockers映射的port(本虚拟机端口) --> targetport(pod暴露出去的端口) --> port(service暴露出去的端口) / nodePort

  • app的port:通常指的是应用程序本身在容器内部监听的端口,例如容器中运行的应用程序监听的端口号。

  • Docker映射的port(本虚拟机端口):这个端口是容器内部端口与宿主机(本虚拟机)端口的映射关系,也就是Docker容器内部端口通过Docker的端口映射机制暴露给宿主机使用的端口。

  • targetport(pod暴露出去的端口):这是指Pod内部容器的端口,Service使用该端口与Pod内的容器通信。

  • port(service暴露出去的端口):这是Service暴露给集群内其他资源使用的端口,当其他资源想要访问该Service时,使用这个端口。

  • NodePort:NodePort是一种类型的Service,它会在每个节点(Node)上开放一个固定的端口(NodePort),外部可以通过该端口访问Service。NodePort是Service类型中的一种,在Kubernetes中用于从集群外部访问服务

所以,Kubernetes 中服务暴露和网络通信的端口映射整体流程应该是:应用程序监听在容器内部的端口(app的port) -> Docker容器端口映射到宿主机的端口 -> Service使用的Pod内部容器端口(targetPort) -> Service暴露给其他资源使用的端口(port) -> NodePort。

这些端口之间的映射关系是Kubernetes中网络通信的基础,确保了容器和服务之间的有效通信。

示例

我们可以看一下示例gulimall-sentinel的端口
在这里插入图片描述

  • 节点端口不可以重复:因为一个service可能有多个微服务如订单服务,库存服务,如果nodePort一样,那么会出现端口占用问题
  • 其他都可以重复:可以理解每一个pod都有自己独立的ip,理解为是一个虚拟机。

所以,暴露出来的端口不可以重复,其他都可以重复。

5、流水线

5.1、Jenkins

官方文档:https://www.jenkins.io/zh/doc/pipeline/tour/getting-started/

Jenkins 是开源 CI&CD 软件领导者, 提供超过 1000 个插件来支持构建、部署、自动化, 满足任何项目的需要。
在这里插入图片描述

流水线

https://www.jenkins.io/zh/doc/book/pipeline/

Jenkins的详细的学习,可以去参考本人的另一篇文档: 云原生系列 - Jenkins

5.2、手动创建流水线

5.2.1、在kubeSphere中创建空流水线
  1. 在kubeSphere中创建流水线gulimall-cicd,暂时先不指定代码仓库
    在这里插入图片描述
  2. 点击创建,先创建一个空流水线
    在这里插入图片描述
  3. 类型Node、label:maven
    在这里插入图片描述
5.2.2、步骤一:拉取代码
5.2.2.1、创建凭证 - gitee-id
  1. 我们gulimall代码在码云里,拉取代码前我们先创建码云的凭证
    在这里插入图片描述
5.2.2.2、添加步骤-git
  1. 填写我们的代码仓库的地址,选择我们刚刚创建的码云凭证,填写我们拉取的代码分支,最后点击确定
    在这里插入图片描述
    在这里插入图片描述
  2. 拉取代码-git 创建好,我们点击 确认 -》 保存
    在这里插入图片描述
    在这里插入图片描述
  3. 验证 拉取代码-git 创建是否正确,我们点击运行,看到运行成功, 则代表 步骤一:拉取代码 创建成功。
    在这里插入图片描述
    在这里插入图片描述
  4. 点击 编辑Jenkinfile,我们可以看到步骤一拉取代码的Jenkinfile内容
    在这里插入图片描述
    在这里插入图片描述
    把kubeSphere上面的Jekinsfile拷贝到我们项目里,进行项目代码里的Jekinsfile创建
5.2.2.3、参数化构建parameters

运行流水线时就需要填入该参数,这个参数可以让我们指定具体哪个微服务参与此次部署,微服务选项制作成下拉栏的形式

  1. 填写需要用到的参数
    在这里插入图片描述
    在这里插入图片描述
  2. 添加shell脚本
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
  3. 点击运行,验证一下参数化构建效果
    在这里插入图片描述
    在这里插入图片描述
  4. 可以看到两个任务都创建成功, 说明我们的shell脚本也成功
    在这里插入图片描述
    我们可以通过日志看一下具体打印内容
    在这里插入图片描述
  5. 点击编辑Jenkinsfile,我们把生成的代码拷贝到项目里的Jenkinsfile
    在这里插入图片描述
5.2.2.4、环境变量environment,容器使用的环境变量
  1. 添加环境变量,gulimall项目代码里也添加该内容
    在这里插入图片描述
  2. 点击运行,进行测试,看看环境变量的值是否也正常获取
    在这里插入图片描述
  3. 可以看到创建成功,并且也成功引用环境变量的值
    在这里插入图片描述
5.2.2.5、Jekinsfile
	pipeline {
	  agent {
	    node {
	      label 'maven'
	    }
	  }
	
	    parameters {
	        string(name:'PROJECT_VERSION',defaultValue: 'v0.0Beta',description:'')
	        string(name:'PROJECT_NAME',defaultValue: '',description:'')
	    }
	    environment {
	      DOCKER_CREDENTIAL_ID = 'harbor-id'
	      GITEE_CREDENTIAL_ID = 'gitee-id'
	      KUBECONFIG_CREDENTIAL_ID = 'demo-kubeconfig'
	      REGISTRY = '192.168.119.133'
	      DOCKERHUB_NAMESPACE = 'gulimall'
	      GITEE_ACCOUNT = 'wang_tianhun'
	      SONAR_CREDENTIAL_ID = 'sonar-token'
	      BRANCH_NAME = 'master'
	    }
	    stages {
	        stage('拉取代码') {
	            steps {
	                git(url: 'https://gitee.com/wang_tianshun/gulimall.git', credentialsId: 'gitee-id', branch: 'master', changelog: true, poll: false)
	                sh 'echo 正在构建 $PROJECT_NAME  版本号:$PROJECT_VERSION'
	            }
	        }
		}
		
	}
5.2.3、步骤二:Sonar代码质量检查
  1. 项目里添加全局maven配置文件
    我们通过以前的devops-java-sample项目的Jenkinsfile-online分析,Sonar指定了全局maven配置文件:configuration/settings.xml,我们的maven镜像地址是使用的阿里云的,所以我们需要在项目里创建maven-settings.xml。配置阿里云镜像,并且指定jdk1.8(mvn构建jar包不指定会使用jdk1.5报错)
    在这里插入图片描述

    <settings>
        <mirrors>
            <mirror>
                <id>alimaven</id>
                <name>aliyun maven</name>
                <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
                <mirrorOf>central</mirrorOf>
            </mirror>
        </mirrors>
        <profiles>
            <profile>
                <id>jdk-1.8</id>
                <activation>
                    <activeByDefault>true</activeByDefault>
                    <jdk>1.8</jdk>
                </activation>
                <properties>
                    <maven.compiler.source>1.8</maven.compiler.source>
                    <maven.compiler.target>1.8</maven.compiler.target>
                    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
                </properties>
            </profile>
        </profiles>
    </settings>
    
  2. 父pom添加sonar需要的插件和指定代码检查的目录

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.auguigu.gulimall</groupId>
        <artifactId>gulimall</artifactId>
        <packaging>pom</packaging>
        <version>0.0.1-SNAPSHOT</version>
        <name>gulimall</name>
        <description>聚合服务</description>
    
        <properties>
            <!-- Sonar -->
            <!-- 代码覆盖率报告的目标文件必须设置为相同的值在父节点和每个模块节点中。然后JaCoCo会把信息加进去同样的报告,这样,它将给出跨模块的代码覆盖率。 -->
            <!--suppress UnresolvedMavenProperty -->
            <sonar.jacoco.reportPaths>${PWD}/./target/jacoco.exec</sonar.jacoco.reportPaths>
            <sonar.groovy.binaries>target/classes</sonar.groovy.binaries>
        </properties>
        <modules>
            <module>gulimall-admin</module>
            <module>gulimall-auth-server</module>
            <module>gulimall-cart</module>
            <module>gulimall-common</module>
            <module>gulimall-coupon</module>
            <module>gulimall-gateway</module>
            <module>gulimall-generator</module>
            <module>gulimall-member</module>
            <module>gulimall-order</module>
            <module>gulimall-product</module>
            <module>gulimall-search</module>
            <module>gulimall-seckill</module>
            <module>gulimall-third-party</module>
            <module>gulimall-ware</module>
            <module>gulimall-test-sso-client</module>
            <module>gulimall-test-sso-server</module>
        </modules>
    
    	<!--sonarqube analysis plugins-->
        <build>
            <plugins>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.8.2</version>
                    <configuration>
                        <append>true</append>
                    </configuration>
                    <executions>
                        <execution>
                            <id>agent-for-ut</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>agent-for-it</id>
                            <goals>
                                <goal>prepare-agent-integration</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>jacoco-site</id>
                            <phase>verify</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.6.0.1398</version>
                </plugin>
            </plugins>
        </build>
    </project>
    
  3. 点击kubeSphere界面的编辑Jekinsfile,添加sonar代码质量分析。项目的Jekinsfile也同步。

    pipeline {
      agent {
        node {
          label 'maven'
        }
      }
    
        parameters {
            string(name:'PROJECT_VERSION',defaultValue: 'v0.0Beta',description:'')
            string(name:'PROJECT_NAME',defaultValue: '',description:'')
        }
        environment {
          DOCKER_CREDENTIAL_ID = 'harbor-id'
          GITEE_CREDENTIAL_ID = 'gitee-id'
          KUBECONFIG_CREDENTIAL_ID = 'demo-kubeconfig'
          REGISTRY = '192.168.119.133'
          DOCKERHUB_NAMESPACE = 'gulimall'
          GITEE_ACCOUNT = 'wang_tianshun'
          SONAR_CREDENTIAL_ID = 'sonar-token'
          BRANCH_NAME = 'master'
        }
        stages {
            stage('拉取代码') {
                steps {
                    git(url: 'https://gitee.com/wang_tianshun/gulimall.git', credentialsId: 'gitee-id', branch: 'master', changelog: true, poll: false)
                    sh 'echo 正在构建 $PROJECT_NAME  版本号:$PROJECT_VERSION'
                    container ('maven') {
                        sh "mvn clean install -Dmaven.test.skip=true -gs `pwd`/mvn-settings.xml"
                    }
                }
            }
    
            stage('sonar代码质量分析') {
              steps {
                container ('maven') {
                  withCredentials([string(credentialsId: "$SONAR_CREDENTIAL_ID", variable: 'SONAR_TOKEN')]) {
                    withSonarQubeEnv('sonar') {
                     sh "echo 当前目录 `pwd`"
                     sh "mvn sonar:sonar -gs `pwd`/mvn-settings.xml -Dsonar.login=$SONAR_TOKEN"
                    }
                  }
                  timeout(time: 1, unit: 'HOURS') {
                    waitForQualityGate abortPipeline: true
                  }
                }
              }
            }
    
        }
    
    }
    

    注意:
    官网文档提供的下载sonar插件
    官方文档:https://github.com/kubesphere/devops-java-sample/blob/sonarqube/Jenkinsfile-online

    sh "mvn sonar:sonar -o -gs `pwd`/configuration/settings.xml -Dsonar.login=$SONAR_TOKEN"
    

    -o 是一个参数,具体含义是指在"离线模式"下运行 Maven。这个参数告诉 Maven 在执行构建或分析时不要尝试下载依赖或插件,而是使用本地缓存中已经存在的内容。如果我们命令加上-o则会提示报错

    [ERROR] No plugin found for prefix 'sonar' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/root/.m2/repository), alimaven (http://maven.aliyun.com/nexus/content/groups/public/)] -> [Help 1]
    

    所以我们的maven命令去掉-o,我们的命令如下:

    sh "mvn sonar:sonar -gs `pwd`/mvn-settings.xml -Dsonar.login=$SONAR_TOKEN"
    
  4. 成功日志
    在这里插入图片描述
    在这里插入图片描述

  5. 访问sonarQube: http://192.168.119.130:30433,查看代码分析
    在这里插入图片描述
    本人的kubeSphere页面没有显示代码质量,网上查到解决办法 kubesphere 流水线 代码质量 不显示,为了继续学习,暂未解决
    在这里插入图片描述

5.2.4、步骤三:构建&推送镜像
  1. stages{}里面继续添加stage (‘构建镜像 & 推送镜像’)步骤,并同步到项目代码中
        stage ('构建镜像 & 推送镜像') {
            steps {
                container ('maven') {
                    sh 'mvn  -Dmaven.test.skip=true -gs `pwd`/mvn-settings.xml clean package'
                    sh 'cd $PROJECT_NAME && docker build -f Dockerfile -t $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER .'
                    withCredentials([usernamePassword(passwordVariable : 'DOCKER_PASSWORD' ,usernameVariable : 'DOCKER_USERNAME' ,credentialsId : "$DOCKER_CREDENTIAL_ID" ,)]) {
                        sh 'echo "$DOCKER_PASSWORD" | docker login $REGISTRY -u "$DOCKER_USERNAME" --password-stdin'
                        sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER'
                    }
                }
            }
        }
  1. 点击 运行,我们构建gulimall-cart微服务镜像,可以看到构建镜像 & 推送镜像成功,并查看成功日志。
    在这里插入图片描述
    在这里插入图片描述
  2. 查看私有镜像仓库-harbor是否有gulimall-cart镜像
    在这里插入图片描述
5.2.5、步骤四:推送最新镜像
  1. stages{}里面继续添加stage (‘推送最新镜像’)步骤,并同步到项目代码中
        stage('推送最新镜像'){
           steps{
                container ('maven') {
                  sh 'docker tag  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:latest '
                  sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:latest '
                }
           }
        }
  1. 点击 运行,我们构建gulimall-cart微服务镜像,可以看到构建镜像 & 推送镜像成功,并查看成功日志。
    在这里插入图片描述
    在这里插入图片描述
  2. 查看私有镜像仓库-harbor是否有gulimall-cart镜像
    在这里插入图片描述
    在这里插入图片描述
    可以看到私有镜像仓库-harbor里存在两个新建的镜像
5.2.6、步骤五:部署到k8s
        stage('部署到k8s') {
          steps {
            input(id: 'deploy-to-dev-$PROJECT_NAME', message: '是否将 $PROJECT_NAME 部署到集群中?')
            kubernetesDeploy(configs: '$PROJECT_NAME/deploy/**', enableConfigSubstitution: true, kubeconfigId: "$KUBECONFIG_CREDENTIAL_ID")
          }
        }
5.2.7、步骤六:发布版本
  1. stages{}里面继续添加stage (‘推送最新镜像’)步骤,并同步到项目代码中
        stage('发布版本'){
          when{
            expression{
              return params.PROJECT_VERSION =~ /v.*/
            }
          }
          steps {
              container ('maven') {
                input(id: 'release-image-with-tag', message: '发布当前版本镜像吗?')
                  withCredentials([usernamePassword(credentialsId: "$GITEE_CREDENTIAL_ID", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                    sh 'git config --global user.email "563540326@qq.com" '
                    sh 'git config --global user.name "wang_tianshun" '
                    sh 'git tag -a $PROJECT_VERSION -m "$PROJECT_VERSION" '
                    sh 'git push http://$GIT_USERNAME:$GIT_PASSWORD@gitee.com/$GITEE_ACCOUNT/gulimall.git --tags --ipv4'
                  }
                sh 'docker tag  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:$PROJECT_VERSION '
                sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:$PROJECT_VERSION '
              }
          }
        }
  1. 修改在每个微服务下创建deploy/devops.yaml
    以前的

    $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:$TAG_NAME
    

    现在的

    $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:latest
    

    在这里插入图片描述

  2. 测试前我们先把线上使用的数据库导入数据,因为我们现在的gulimall-mysql-master是有状态服务,外网无法访问。我们再创建一个指定工作负载服务,暴露对外接口。

    1. 选择指定工作负载服务
      在这里插入图片描述

    2. 填写基本信息,名称:gulimall-mysql-master-node-port
      在这里插入图片描述

    3. 指定工作负载
      在这里插入图片描述
      在这里插入图片描述

    4. 创建,暴露外网访问端口
      在这里插入图片描述
      在这里插入图片描述

    5. navict连接数据库端口号为31564,并且测试没有问题
      在这里插入图片描述
      我们把以前的数据库都导入到现在k8s-mysql-master

5.3、代码创建流水线

5.3.1、Jenkinsfile

根据上面 5.2、手动创建流水线,我们得到最终的Jenkinsfile,放到我们的项目代码里
在这里插入图片描述

pipeline {
  agent {
    node {
      label 'maven'
    }

  }
  
  parameters {
      string(name:'PROJECT_VERSION',defaultValue: 'v0.0Beta',description:'')
      string(name:'PROJECT_NAME',defaultValue: '',description:'')
  }
  
  environment {
      DOCKER_CREDENTIAL_ID = 'harbor-id'
      GITEE_CREDENTIAL_ID = 'gitee-id'
      KUBECONFIG_CREDENTIAL_ID = 'demo-kubeconfig'
      REGISTRY = '192.168.119.133'
      DOCKERHUB_NAMESPACE = 'gulimall'
      GITEE_ACCOUNT = 'wang_tianshun'
      SONAR_CREDENTIAL_ID = 'sonar-token'
      BRANCH_NAME = 'master'
  }
  
  stages {
    stage('拉取代码') {
      steps {
        git(url: 'https://gitee.com/wang_tianshun/gulimall.git', credentialsId: 'gitee-id', branch: 'master', changelog: true, poll: false)
        sh 'echo 正在构建 $PROJECT_NAME  版本号:$PROJECT_VERSION 将会提交给 $REGISTRY/$DOCKERHUB_NAMESPACE 镜像仓库'
      }
    }
    
    stage('sonar代码质量分析') {
      steps {
                container ('maven') {
          sh "mvn clean install -Dmaven.test.skip=true -gs `pwd`/mvn-settings.xml"
        }
        container ('maven') {
          withCredentials([string(credentialsId: "$SONAR_CREDENTIAL_ID", variable: 'SONAR_TOKEN')]) {
            withSonarQubeEnv('sonar') {
             sh "echo 当前目录 `pwd`"
             sh "mvn sonar:sonar -gs `pwd`/mvn-settings.xml -Dsonar.login=$SONAR_TOKEN"
            }
          }
          timeout(time: 1, unit: 'HOURS') {
            waitForQualityGate abortPipeline: true
          }
        }
      }
    }
  
    stage ('构建镜像 & 推送快照镜像') {
      steps {
          container ('maven') {
              sh 'mvn  -Dmaven.test.skip=true -gs `pwd`/mvn-settings.xml clean package'
              sh "echo 当前目录 `pwd`"
              sh 'cd $PROJECT_NAME && docker build -f Dockerfile -t $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER .'
              withCredentials([usernamePassword(passwordVariable : 'DOCKER_PASSWORD' ,usernameVariable : 'DOCKER_USERNAME' ,credentialsId : "$DOCKER_CREDENTIAL_ID" ,)]) {
                  sh 'echo "$DOCKER_PASSWORD" | docker login $REGISTRY -u "$DOCKER_USERNAME" --password-stdin'
                  sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER'
              }
          }
      }
    }
    
    stage('推送最新镜像'){
        when{
            branch 'master'
        }
       steps{
            container ('maven') {
              sh 'docker tag  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:latest '
              sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:latest '
            }
       }
    }
    
    stage('部署到k8s') {
      steps {
        input(id: "deploy-to-dev-$PROJECT_NAME", message: "是否将 $PROJECT_NAME 部署到集群中?")
        kubernetesDeploy(configs: "$PROJECT_NAME/deploy/**", enableConfigSubstitution: true, kubeconfigId: "$KUBECONFIG_CREDENTIAL_ID")
      }
    }

    stage('发布版本'){
      when{
        expression{
          return params.PROJECT_VERSION =~ /v.*/
        }
      }
      steps {
          container ('maven') {
            input(id: 'release-image-with-tag', message: '发布当前版本镜像吗?')
              withCredentials([usernamePassword(credentialsId: "$GITEE_CREDENTIAL_ID", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                sh 'git config --global user.email "563540326@qq.com" '
                sh 'git config --global user.name "wang_tianshun" '
                sh 'git tag -a $PROJECT_VERSION-$PROJECT_NAME -m "$PROJECT_VERSION" '
                sh 'git push http://$GIT_USERNAME:$GIT_PASSWORD@gitee.com/$GITEE_ACCOUNT/gulimall.git --tags --ipv4'
              }
            sh 'docker tag  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:SNAPSHOT-$BRANCH_NAME-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:$PROJECT_VERSION '
            sh 'docker push  $REGISTRY/$DOCKERHUB_NAMESPACE/$PROJECT_NAME:$PROJECT_VERSION '
          }
      }
    }
    
  }
}
5.3.2、kubeSphere创建指定仓库流水线
  1. 填写基本信息
    • 名称:gulimall-jekinsfile-cicd
    • 描述信息:谷粒商城自动微服务部署,参数化构建
      在这里插入图片描述
  2. 选择一个代码仓库
    在这里插入图片描述
    在这里插入图片描述
  3. 高级设置
    在这里插入图片描述
5.3.3、流水线部署所有微服务

在这里插入图片描述
我们可以看到12个微服务全部部署完成,并且都处于运行中状态
在这里插入图片描述
在这里插入图片描述

十一、谷粒商城上线

1、部署流程

在这里插入图片描述
接下来,我们根据部署流程把谷粒商城上线

2、k8s 部署 nginx

2.1、Docker镜像操作

我们以前开发时,所有的静态资源和一些反向代理配置在nginx上的,现在我们将正在运行的nginx打包成镜像,上传到我们的私有仓库-Harbor,然后直接用该原有的nginx部署服务就可以直接使用

  1. 调整nginx.conf的上游服务器地址
    根据 部署流程 可知,我们的nginx要负载均衡到网关,但是我们现在的项目都部署在k8s上,所以我们nginx要修改上游服务器地址,可以负载到k8s的网关服务。

    [root@localhost ~]# cd /mydata/nginx/conf/
    [root@localhost conf]# ls
    conf.d  fastcgi_params  koi-utf  koi-win  mime.types  modules  nginx.conf  scgi_params  uwsgi_params  win-utf
    [root@localhost conf]# cp nginx.conf nginx.conf.bak
    [root@localhost conf]# ls
    conf.d  fastcgi_params  koi-utf  koi-win  mime.types  modules  nginx.conf  nginx.conf.bak  scgi_params  uwsgi_params  win-utf
    [root@localhost conf]# vi nginx.conf
    

    在这里插入图片描述

    • 端口号为gulimall-gateway微服务devops.yaml暴露的端口号:31005
    • ip为我们k8s集群服务的ip,随便哪一台都可以访问:192.168.119.130、192.168.119.131、192.168.119.132
  2. 将正在运行的nginx打包成镜像

    docker commit -a "wts" -m "nginx" c72f12c0c303 gulimall-nginx:v1.0
    

    在这里插入图片描述
    1、docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
    2、OPTIONS 说明:

    • -a :提交的镜像作者;
    • -c :使用 Dockerfile 指令来创建镜像;
    • -m :提交时的说明文字;
    • -p :在 commit 时,将容器暂停。
  3. 将镜像打标签 & 推送

    登录Harbor

    docker login -u admin -p Harbor12345 http://192.168.119.133
    

    将镜像打标签上传到私有仓库-Harbor的gulimall项目里面

    docker tag gulimall-nginx:v1.0 192.168.119.133/gulimall/gulimall-nginx:v1.0
    
    docker push 192.168.119.133/gulimall/gulimall-nginx:v1.0
    

    在这里插入图片描述
    在这里插入图片描述

  4. 登录Harbor查看镜像
    在这里插入图片描述

  5. 最终镜像操作
    我们部署打包好的gulimall-nginx:v1.0镜像发现没有静态文件,因为我们使用docker commit命令的时候没法将静态文件打包成镜像,这里我们使用雷神提前准备好的Dockerfile和静态文件压缩包和配置压缩包(nginx.cnf改为自己的网关服务地址)。切记,解压缩格式一定要使用正确方法,不能随意手动改动
    在这里插入图片描述
    在这里插入图片描述

    docker build -t gulimall-nginx:v1.1 -f Dockerfile .
    

    在这里插入图片描述
    将镜像打标签上传到私有仓库-Harbor的gulimall项目里面

    docker tag gulimall-nginx:v1.1 192.168.119.133/gulimall/gulimall-nginx:v1.1
    
    docker push 192.168.119.133/gulimall/gulimall-nginx:v1.1
    

    在这里插入图片描述
    可以看到我们的私有镜像仓库-Harbor已经存在该镜像
    在这里插入图片描述

2.2、创建服务 - gulimall-nginx

  1. 选择无状态服务
    在这里插入图片描述
  2. 填写基本信息,名称:gulimall-nginx
    在这里插入图片描述
  3. 容器镜像
    在这里插入图片描述
    在这里插入图片描述
  4. 挂载存储
    在这里插入图片描述
  5. 创建,添加外网访问
    在这里插入图片描述
  6. 测试
    在这里插入图片描述
    可以看到对外暴露的端口为32498,我们随便找一个服务的ip进行访问:http://192.168.119.130:32498/
    在这里插入图片描述
  7. 我们进入容器,查看静态资源是否都存在,可以看到静态文件都有
    在这里插入图片描述

3、创建应用路由

  1. 在创建应用路由之前,需要先启用外网访问入口,即网关。这一步是创建对应的应用路由控制器,负责接收项目外部进入的流量,并将请求转发到对应的后端服务。
    使用项目管理员 project-admin设置外网访问,选择 「项目设置」 → 「外网访问」,点击 「设置网关」。
    可参考 多租户管理快速入门
    在这里插入图片描述
    在弹窗中,选择LoadBalancer,不添加注解,然后点击 「保存」
    在这里插入图片描述
    在这里插入图片描述

  2. 创建应用路由
    在这里插入图片描述

  3. 填写基本信息,名称:gulimall-com在这里插入图片描述

  4. 路由规则
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  5. 创建
    在这里插入图片描述
    在这里插入图片描述

  6. 在C:\Windows\System32\drivers\etc\hosts文件里修改域名对应的ip,都改为k8s创建应用路由的网关地址

    #----------k8s----------
    192.168.119.130 gulimall.com
    192.168.119.130 search.gulimall.com
    192.168.119.130 item.gulimall.com
    192.168.119.130 auth.gulimall.com
    192.168.119.130 cart.gulimall.com
    192.168.119.130 order.gulimall.com
    192.168.119.130 member.gulimall.com
    192.168.119.130 seckill.gulimall.com
    
  7. 测试,访问:http://gulimall.com/static/search/img/01.png
    在这里插入图片描述

  8. 添加所有的域名到路由规则中
    在这里插入图片描述
    在这里插入图片描述

4、访问谷粒商城

访问地址:http://gulimall.com
在这里插入图片描述

5、部署vue项目

5.1、Docker镜像制作

  1. 修改线上环境配置,将api接口请求地址改为线上网关地址
    在这里插入图片描述

  2. 执行命令npm run build构建,打包

    npm run build
    

    在这里插入图片描述

    可以看到项目里多了一个dist文件夹

    在这里插入图片描述

    这就是我们vue打包生成的文件

    在这里插入图片描述

  3. Docker镜像制作
    我们使用2345好压软件,把它压缩成dist.tar.gz,在使用提供的Dockerfile,制作镜像

    FROM nginx
    MAINTAINER leifengyang
    ADD dist.tar.gz /usr/share/nginx/html
    EXPOSE 80
    ENTRYPOINT nginx -g "daemon off;"
    

    在这里插入图片描述

    先登录私有镜像仓库-harbor

    docker login -u admin -p Harbor12345 http://192.168.119.133
    

    构建镜像

    docker build -t gulimall-admin-vue-app:v1.0 -f Dockerfile .
    

    在这里插入图片描述
    将镜像打标签上传到私有仓库-Harbor的gulimall项目里面

    docker tag gulimall-admin-vue-app:v1.0 192.168.119.133/gulimall/gulimall-admin-vue-app:v1.0
    
    docker push 192.168.119.133/gulimall/gulimall-admin-vue-app:v1.0
    

    在这里插入图片描述

    可以看到我们的私有镜像仓库-Harbor已经存在该镜像
    在这里插入图片描述

5.2、创建服务 - gulimall-admin-vue-app

  1. 选择无状态服务
    在这里插入图片描述
  2. 容器镜像在这里插入图片描述
    在这里插入图片描述
  3. 创建,并指定外网访问
    在这里插入图片描述
    在这里插入图片描述
  4. 测试,随便选择一台服务ip,然后拼接暴露端口30563,进行访问:http://192.168.119.130:30563/#/login
    在这里插入图片描述

5.3、以域名方式访问谷粒商城管理系统

  1. 路由设置,添加admin.gulimall.com,指定到谷粒商城管理系统的服务在这里插入图片描述
  2. 在C:\Windows\System32\drivers\etc\hosts文件里新增域名,添加192.168.119.130 admin.gulimall.com
#----------k8s----------
192.168.119.130 gulimall.com
192.168.119.130 search.gulimall.com
192.168.119.130 item.gulimall.com
192.168.119.130 auth.gulimall.com
192.168.119.130 cart.gulimall.com
192.168.119.130 order.gulimall.com
192.168.119.130 member.gulimall.com
192.168.119.130 seckill.gulimall.com
192.168.119.130 admin.gulimall.com
  1. 测试,访问:http://admin.gulimall.com
    在这里插入图片描述

毕业了~

学习尚硅谷发布的谷粒商城项目课程是一个深入了解现代化企业级应用开发的良好途径。这个项目涵盖了多个技术领域和实际应用场景,下面是一个总结:

项目背景和目标:
谷粒商城项目旨在实现一个完整的电商平台,涵盖了用户注册登录、商品管理、购物车、订单管理、支付系统等核心功能,通过这些功能模块学习实际应用开发中的各种技术和解决方案。

技术栈和工具:

  • 前端:使用 Vue.js 框架构建单页面应用(SPA),采用 Element UI 等组件库进行界面设计和开发。
  • 后端:采用 Spring Cloud 微服务架构,包括 Spring Boot、Spring Cloud Alibaba(Nacos、Sentinel、Feign、Gateway等)、MyBatis 等技术。
  • 数据库:使用 MySQL 关系型数据库进行数据存储和管理。
  • 消息中间件:使用 RabbitMQ 进行分布式消息通信。
  • 分布式缓存:使用 Redis 实现数据缓存和提升系统性能。
  • 持续集成和部署:通过 Jenkins 等工具实现持续集成和自动化部署。
  • 容器化技术:使用 Docker 进行应用容器化,配合 Kubernetes 实现容器集群管理。

学习收获:

  • 微服务架构设计:了解和实践了如何基于 Spring Cloud 实现微服务架构,包括服务注册与发现、配置中心、服务网关等核心组件。
  • 前后端分离开发:掌握了前后端分离开发模式下的协作和通信方式,以及 RESTful API 的设计和使用。
  • 分布式事务处理:学习了如何处理分布式系统中的事务问题,如何保证数据的一致性和可靠性。
  • 性能优化和安全:探索了在大规模应用中如何进行性能优化和安全防护,包括负载均衡、限流、熔断、认证授权等方面。
  • 项目实战经验:通过完成项目,积累了大型应用开发和协作的实战经验,了解了开发中的常见问题和解决方法。

未来拓展和深入学习:

  • 进一步学习和掌握云原生技术栈,如使用 Istio 等服务网格实现微服务的流量管理和安全控制。
  • 深入了解分布式存储和大数据处理技术,以支持更复杂的数据分析和业务扩展。

总体而言,通过学习谷粒商城项目,不仅掌握了多种技术栈和开发工具的使用,还积累了实际项目开发中的经验和技能,为未来的职业发展和技术深造奠定了坚实的基础。

  • 30
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值