K8S--部署SpringBoot调用MySQL(实战)

2024-01-08 06:25:38

原文网址:K8S--部署SpringBoot调用MySQL(实战)-CSDN博客

简介

本文介绍K8S部署SpringBoot调用MySQL的实战案例。

分享Java真实高频面试题,吊打面试官: Java后端真实面试题大全 - 自学精灵
分享靠谱的Java高级实战,包含:高并发、架构、全局处理等:JavaWeb高级实战 - 自学精灵

1.部署MySQL

见:K8S--部署SpringBoot调用MySQL(实战)-CSDN博客

部署之后,创建数据库和表:

DROP DATABASE IF EXISTS mp;
CREATE DATABASE mp DEFAULT CHARACTER SET utf8;
USE mp;

DROP TABLE IF EXISTS `t_user`;
SET NAMES utf8mb4;

CREATE TABLE `t_user`
(
    `id`           BIGINT(0) NOT NULL,
    `user_name`    VARCHAR(64) NOT NULL COMMENT '用户名(不能重复)',
    `nick_name`    VARCHAR(64) NULL COMMENT '昵称(可以重复)',
    `email`        VARCHAR(64) COMMENT '邮箱',
    `create_time`  DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time`  DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
    `deleted_flag` BIGINT(0) NOT NULL DEFAULT 0 COMMENT '0:未删除 其他:已删除',
    PRIMARY KEY (`id`) USING BTREE,
    UNIQUE KEY `index_user_name_deleted_flag` (`user_name`, `deleted_flag`),
    KEY `index_create_time`(`create_time`)
) ENGINE = InnoDB COMMENT = '用户';

INSERT INTO `t_user` VALUES (1, 'knife', '刀刃', 'abc@qq.com', '2021-01-23 09:33:36', '2021-01-23 09:33:36', 0);
INSERT INTO `t_user` VALUES (2, 'sky', '天蓝', '123@qq.com', '2021-01-24 18:12:21', '2021-01-24 18:12:21', 0);
INSERT INTO `t_user` VALUES (3, 'aa', '昵称1', '333@qq.com', '2021-01-12 13:12:21', '2021-01-12 13:12:21', 0);
INSERT INTO `t_user` VALUES (4, 'bb', '昵称2', '444@qq.com', '2021-02-11 18:12:21', '2021-02-11 18:12:21', 0);
INSERT INTO `t_user` VALUES (5, 'cc', '昵称3', '555@qq.com', '2021-03-24 18:12:21', '2021-03-24 18:12:21', 0);

2.创建SpringBoot项目

application.yml

spring:
  application:
    name: springboot-mysql
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 用${}表达式替代,镜像部署时可以使用环境变量指定
    url: jdbc:mysql://${MYSQL_HOST:mysql}:${MYSQL_PORT:3306}/mp?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: ${MYSQL_USERNAME:root}
    password: ${MYSQL_PASSWORD:222333}

#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

logging:
  file:
    # 根据pod名字生成日志文件
    name: log/${POD_NAME}.log
  level:
    root: info

Controller

package com.knife.example.business.user.controller;

import com.knife.example.business.user.bo.UserBO;
import com.knife.example.business.user.entity.User;
import com.knife.example.business.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "用户")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("查找")
    @GetMapping("find")
    public List<User> find(UserBO userBO) {
        return userService.lambdaQuery()
                .like(StringUtils.hasText(userBO.getUserName()), User::getUserName, userBO.getUserName())
                .list();
    }
}

Dockerfile

# 基础镜像使用java
# 也可以用:FROM openjdk:8
FROM java:8

# 作者
MAINTAINER knife <xxx@xx.com>

# 不是真正的发布端口,只是容器部署人员与建立image的人员之间的交流。
# 即:建立image的人员告诉容器布署人员容器应该映射哪个端口给外界
EXPOSE 8080

# 指定临时文件目录,此步骤非必须。如果Java里要操作文件,就要添加这个配置
# 会在主机 /var/lib/docker 创建文件,连接到容器的/tmp。SpringBoot的内嵌Tomcat默认使用/tmp作为工作目录
VOLUME /tmp

# 将jar包添加到容器中并更名为app.jar
ADD *.jar app.jar

ENV JAVA_OPTS=""

# ENTRYPOINT:docker启动时,运行的命令。这里直接运行jar服务。
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -jar /app.jar --spring.profiles.active=default" ]

pom.xml

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.knife</groupId>
    <artifactId>springboot-mysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mysql</name>
    <description>Demo project for Docker Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.生成并推送应用的docker镜像

详见:K8S--部署SpringBoot项目实战-CSDN博客

这个链接里有harbor的搭建及项目的创建、SpringBoot项目的打包等。

这里只展示命令:

docker rmi 192.168.5.193:15001/custom_image/custom_springboot-mysql:1.0 --force
docker build -t 192.168.5.193:15001/custom_image/custom_springboot-mysql:1.0 . --no-cache
docker push 192.168.5.193:15001/custom_image/custom_springboot-mysql:1.0

推送上去后,可以在harbor里看到:

?

4.编写应用的K8S配置文件

1.创建命名空间

创建名为java-app-namespace.yaml的文件,内容如下:

# 创建命名空间
apiVersion: v1
kind: Namespace
metadata:
  name: java-app
  labels:
    name: java-app

创建命名空间:

kubectl apply -f java-app-namespace.yaml

2.创建应用的K8S配置文件

创建应用的k8s配置文件:k8s.yaml,内容如下:

# 创建Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: springboot-mysql-deployment
  namespace: java-app
  labels:
    app: springboot-mysql #与Service的selector对应
spec:
  # 副本的数量
  replicas: 2
  selector:
    # 选择Pod
    matchLabels:
      app: springboot-mysql
  # 选择或创建的Pod的模板
  template:
    metadata:
      # 与Deployment的selector对应
      labels:
        app: springboot-mysql
    spec:
      imagePullSecrets:
        - name: harbor-secret

      containers:
        - image: 192.168.5.193:15001/custom_image/custom_springboot-mysql:1.0
          name: custom-springboot-mysql-1-0
          imagePullPolicy: Always
          env:
            - name: TZ
              value: Asia/Shanghai
            - name: MYSQL_HOST
              value: mysql-service.db
            - name: MYSQL_PORT
              value: "3306"
            - name: MYSQL_USERNAME
              value: root
            - name: MYSQL_PASSWORD
              value: "123456"
            - name: POD_NAME   #用Pod名字给日志文件命名,防止多个pod日志输出到同一日志文件
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
          ports:
            - containerPort: 8080
              name: pod-8080
          # 容器内的路径
          volumeMounts:
            - name: log
              mountPath: /log/
      # 主机的路径
      volumes:
        - name: log #和volumeMounts中的内容要对应
          hostPath:
            path: /work/devops/k8s/app/springboot-mysql/log/
            type: DirectoryOrCreate

---
# 创建Service
apiVersion: v1
kind: Service
metadata:
  name: springboot-mysql-service
  namespace: java-app
  labels:
    app: springboot-mysql
spec:
  ports:
    - name: springboot-mysql-port
      port: 9001   # Service监听的端口
      targetPort: 8080  # pod自身暴露的端口。对应Deployment的containerPort
      # 对外的端口号
      nodePort: 30006
  # 选择Deployment
  selector:
    app: springboot-mysql
  # NodePort类型可以对外暴露端口
  type: NodePort

注意

k8s在与其他服务通信时,需要注意主机指定

  1. 如果命名空间相同,host用对方服务的Service。
  2. 如果命名空间相同,host用对方服务的Service:Namespace。

本处mysql的服务名是mysql-service,命名空间是db,所以是:mysql-service:db

5.启动应用的Pod

kubectl apply -f k8s.yaml

6.查看启动结果并测试

1.查看pods

kubectl get pods -A

?结果:

2.查看dashboard

3.查看日志?

可以发现,每个pod都单独生成了日志。(pod在销毁、重新生成后,会生成新的日志文件。)

4.测试接口

访问接口文档:http://192.168.5.193:30006/doc.html

测试接口:(成功查到数据库数据)?

文章来源:https://blog.csdn.net/feiying0canglang/article/details/135415853
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。