5.go-zero集成gorm 和 go-redis

  1. 安装gorm相关依赖

    bash 复制代码
    go get -u gorm.io/gorm
    
    go get -u gorm.io/driver/mysql
  2. 编写配置文件

  3. 编写model加载配置

  1. 在main中加载配置文件
go 复制代码
var configFile = flag.String("f", "etc/auth.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

  ....
}

InitGorm连接MySQL

ServiceContext中给DB赋值

go 复制代码
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package svc

import (
	"im-server/core"
	"im-server/im_auth/auth_api/internal/config"

	"gorm.io/gorm"
)

type ServiceContext struct {
	Config config.Config
	DB     *gorm.DB
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config: c,
		DB:     core.InitGorm(c.MySql.DataSource),
	}
}

如法炮制,我们下面开始集成 go-redis

  1. 安装依赖
bash 复制代码
github.com/redis/go-redis@upgrade 

2.在yaml配置文件中增加redis相关配置

bash 复制代码
Name: auth
Host: 0.0.0.0
Port: 8889
MySql:
  DataSource: root:a12345678@tcp(127.0.0.1:3306)/my_qq?charset=utf8mb4&parseTime=True&loc=Local
Redis:
  Host: 127.0.0.1
  Port: 6379
  Password: ""
  1. 修改config文件
bash 复制代码
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package config

import "github.com/zeromicro/go-zero/rest"


type Config struct {
	rest.RestConf
	MySql struct {
		DataSource string
	}

	Redis struct {
		Host     string
		Port     int
		Password string
	}
}
go 复制代码
package core

import (
	"fmt"
	"github.com/redis/go-redis"
)

func InitRedis(host string, port int) *redis.Client {
	rdb := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", host, port),
		Password: "", // No password set
		DB:       0,  // Use default DB
	})
	return rdb
}
bash 复制代码
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package svc

import (
	"github.com/redis/go-redis"
	"im-server/core"
	"im-server/im_auth/auth_api/internal/config"

	"gorm.io/gorm"
)

type ServiceContext struct {
	Config config.Config
	DB     *gorm.DB
	Redis  *redis.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config: c,
		DB:     core.InitGorm(c.MySql.DataSource),
		Redis:  core.InitRedis(c.Redis.Host, c.Redis.Port),
	}
}
相关推荐
为何创造硅基生物4 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好4 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
星寂樱易李5 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
仰泳之鹅5 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆5 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
姚不倒6 小时前
Go语言进阶:接口、错误处理与并发编程(goroutine/channel/context)
云原生·golang
candyTong6 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
cen__y6 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
AI人工智能+电脑小能手6 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
GetcharZp7 小时前
GitHub 2.4 万 Star!D2 正在重新定义程序员画图方式
后端