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),
	}
}
相关推荐
沐知全栈开发3 小时前
Perl 数据库连接
开发语言
森叶4 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
qq_316837754 小时前
uni.chooseMedia 读取base64 或 二进制
开发语言·前端·javascript
方圆工作室4 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
小二·5 小时前
Python Web 开发进阶实战:混沌工程初探 —— 主动注入故障,构建高韧性系统
开发语言·前端·python
Lkygo5 小时前
LlamaIndex使用指南
linux·开发语言·python·llama
进阶小白猿5 小时前
Java技术八股学习Day20
java·开发语言·学习
代码村新手5 小时前
C++-类和对象(中)
java·开发语言·c++
葵花楹5 小时前
【JAVA课设】【游戏社交系统】
java·开发语言·游戏
赵谨言5 小时前
Python串口的三相交流电机控制系统研究
大数据·开发语言·经验分享·python