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),
	}
}
相关推荐
余槐i28 分钟前
PostgreSQL 函数索引报错 must be immutable:3种绕法与代价
数据库·后端·sql·postgresql·性能优化
需要8261 小时前
Spring Bean 生命周期:从实例化到销毁的完整钩子
java·后端·spring
死磕音视频2 小时前
让小模型做选择题:限定候选项并读取 logits 概率的入门实践(附 Python 代码)
开发语言·python·大模型·文本分类·transformers
凤山老林2 小时前
Spring Boot 接入国密 SM2/SM3/SM4 的一些实践记录
spring boot·后端·python
伯恩bourne3 小时前
Spring Boot Bean 注册的两种方式:@Component 家族 vs @Configuration + @Bean
java·spring boot·后端
张彦峰ZYF3 小时前
停顿短不等于延迟低:G1、ZGC 与低延迟服务的目标分野、代价账本与选型标定
后端·回收暂停、应用停止总时长·到达安全点、分配停滞·屏障吃吞吐、并发线程吃核心·并发窗口吃堆余量·分区式靠挑回收集兑现目标·染色指针式不支持压缩引用
pride.li4 小时前
第03章 Python 教程-基础语法:注释与变量
服务器·前端·后端·python·算法·计算机视觉
顽疲4 小时前
Java vue 养老系统源码详解:月账单 care_month_bill 与 Quartz 扣费 Job 实践
java·开发语言·vue.js·vue养老·springboot养老·java养老
Wang's Blog4 小时前
Java 项目实战: 交友项目 - 安装开发工具与环境准备
java·开发语言·交友
upala4 小时前
【仓颉语言入门 · 第二篇 第 6 课】
后端