k8s使用外部mysql做内部服务
创建 mysql-endpoints.yaml
1apiVersion: v1
2kind: Endpoints
3metadata:
4 name: mysql-dev
5 namespace: default
6subsets:
7 - addresses:
8 - ip: 10.1.0.32
9 ports:
10 - port: 3306
创建mysql-service.yaml
1apiVersion: v1
2kind: Service
3metadata:
4 name: mysql-dev
5spec:
6 ports:
7 - port: 3306
8
或者
1apiVersion: v1
2kind: Service
3metadata:
4 name: mysql-dev
5 namespace: default
6spec:
7 clusterIP: 10.1.61.45
8 ports:
9 - port: 3306
10 targetPort: 3306
11 protocol: TCP
使用数据库服务
main.go
1package main
2
3import (
4 "database/sql"
5 "fmt"
6 _ "github.com/go-sql-driver/mysql"
7 "net/http"
8)
9
10func IndexHandler(w http.ResponseWriter, r *http.Request) {
11 _, _ = fmt.Fprintln(w, "hello rushui")
12}
13
14func RowsHandler(w http.ResponseWriter, r *http.Request) {
15 //第⼀步:打开数据库,格式是 ⽤户名:密码@/数据库名称?编码⽅式
16 db, err := sql.Open("mysql", "root:root@tcp(mysql-dev:3306)/test?charset=utf8")
17 if err != nil {
18 fmt.Println(err)
19 }
20 //关闭数据库
21 var id int
22 var name string
23 //查询数据,指定字段名,返回sql.Rows结果集
24 rows, err := db.Query("select id,name from user")
25 if err != nil {
26 fmt.Println(err)
27 }
28 defer rows.Close()
29 for rows.Next() {
30 _ = rows.Scan(&id, &name)
31 _, _ = fmt.Fprintln(w, name)
32 }
33}
34
35func main() {
36 http.HandleFunc("/", IndexHandler)
37 http.HandleFunc("/rows", RowsHandler)
38 _ = http.ListenAndServe(":8081", nil)
39}
发布日期:2023-03-12 19:41 字数:197 用时
标签云
alpine(1) api网关(1) async(1) await(1) centos(4) cli(1) client-go(1) debug(1) docker(10) docker-compose(1) dockerfile(1) embed(1) es6(1) etcd(1) etcdctl(1) freemesh(2) git(6) go(5) go-zeus(5) goland(2) golang(7) grafana(2) grpc(5) grpcurl(1) homebrew(1) homedir(1) http(2) hugo(1) java(2) javascript(3) job(1) js(1) json(1) k8s(16) k8s部署指南(1) kubebuilder(1) kubectl(4) kubernetes(1) linux(2) localecompare(1) lombok(1) metrics(2) mock(1) mysql(1) npm(1) nsenter(1) nvm(1) pnpm(2) pprof(1) prettier(1) prometheus(2) protobuf3(1) protoc(1) qiankun(1) request(1) scss(1) servicemesh(1) spring(1) springcloud->freemesh(1) ssh(2) systemctl(1) tcpdump(1) typescript(2) vite(2) vscode(2) vue(8) vue-admin(2) vue3(1) webssh(1) xtermjs(1) xxl-job(1) yarn(1) zookeeper(1) 云原生(4) 云原生框架(1) 介绍(1) 单体架构->freemesh(1) 单元化(1) 博客(1) 压缩(1) 可观测(1) 后台管理系统(1) 命名规范(1) 多云多活(1) 如水网(1) 安全(1) 安装(1) 容器(2) 开发联调神器(1) 微前端(1) 微服务(2) 微服务架构->freemesh(1) 微服务框架(1) 快速开始(1) 控制面(1) 数据面(1) 文集(2) 服务发现(1) 服务网格(1) 流量泳道(1) 流量管理(1) 监控告警(1) 端口映射(1) 证书(1) 负载均衡(1) 配置(1)