springboot整合mysql5.7_每天五分钟写K8(四):SpringBoot与mysql整合
在第一節中我們創建了mysql的Service,上一節我們運行了Spring-boot的項目。這一節我們將兩個項目結合起來,讓spring-boot訪問mysql服務。
一、給Spring-boot項目的Deployment添加環境變量
Kubernetes運行著大量的Service,那么必然需要服務發現機制。由于一個Service的Cluster IP不會發生改變,那么Kubenetes就使用了環境變量來解決了這個問題。使用時將要使用的服務添加到環境變量即可。在上節的yaml文件中修改spec.template.spec.containers項即可。
containers:- name: springboot-demoimage: k8s-boot:2.0imagePullPolicy: Neverports:- containerPort: 8080env:-?name:MYSQL_SERVICE_HOSTvalue: 'mysql'- name: MYSQL_SERVICE_PORTvalue: '3306'
二、準備可訪問數據的Spring-boot項目
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://${MYSQL_SERVICE_HOST:localhost}:${MYSQL_SERVICE_PORT:3306}/test?useUnicode=true&characterEncoding=utf-8username: rootpassword: 123456
三、按上節部署方式進行部署
上傳鏡像是一個比較繁瑣的工作,我提供了上傳到指定主機的腳本image_deploy.py在github上。
部署完成后在瀏覽器中測試:http://:30000/user/findAll。最終會返回以下錯誤:
java.sql.SQLSyntaxErrorException: Unknown database 'test'
這是因為我們的數據庫服務尚未進行正確的初始化。
四、初始化數據庫
初始化數據庫有很多種方式,例如:
暴露Service的NodePort,然后用圖形化客戶端連接,執行SQL語句
在Pod中運行mysql客戶端,執行SQL語句
借助ConfigMap,啟動Pod時獲取初始化SQL語句并執行
第一種咱們已經接觸過了,第三種尚未學習。今天我們就采用第二種初始化。
第一步要獲取mysql?pod的名稱:
$?kubectl?get?pod??-l?app=mysqlNAME READY STATUS RESTARTS AGEmysql-qkfcd 1/1 Running 0 4d22h
第二步進入容器:
$ kubectl?exec?-it?mysql-qkfcd?/bin/bashroot@mysql-qkfcd:/#
第三步連接mysql服務,執行SQL
root@mysql-qkfcd:/$?mysql?-uroot?-pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 18Server version: 8.0.17 MySQL Community Server - GPLCopyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> create database test;Query OK, 1 row affected (0.00 sec)mysql> use test;Database changedmysql> CREATE TABLE `user` (-> `id` int(11) NOT NULL AUTO_INCREMENT,-> `user_name` varchar(45) NOT NULL,-> `password` varchar(45) NOT NULL,-> PRIMARY KEY (`id`)-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;Query OK, 0 rows affected, 1 warning (0.01 sec)mysql> exit
最后退出即可。
代碼下載:
https://github.com/loveoobaby/blog_code
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的springboot整合mysql5.7_每天五分钟写K8(四):SpringBoot与mysql整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 密码破解工具怎么用 使用密码破解工具的方
- 下一篇: mysql5.5 配置_MySQL5.5