go-zero中使用xorm和redis

xorm的封装

package basics

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
)

func Init(dataSource string) *xorm.Engine {
	engine, err := xorm.NewEngine("mysql", dataSource)
	if err != nil {
		fmt.Println("数据库连接失败:", err)
		return nil
	}
	engine.ShowSQL(true)
	return engine
}

redis的封装

package redisClient

import (
	"go/application/basics/internal/config"

	"github.com/go-redis/redis"
)

func Init(c config.Config) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     c.Redis.Addr,
		Password: c.Redis.PassWord,
		DB:       0,
	})
}

然后我都将其挂在了svc包下,具体如下:

package svc

import (
	"go/application/basics/internal/config"
	"go/application/basics/internal/middleware"
	"go/application/basics/service/basics"
	"go/application/basics/service/redisClient"

	"github.com/go-redis/redis"
	"github.com/zeromicro/go-zero/rest"
	"xorm.io/xorm"
)

type ServiceContext struct {
	Config          config.Config
	Engine          *xorm.Engine
	AuthInterceptor rest.Middleware
	Redis           *redis.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config:          c,
		Engine:          basics.Init(c.DB.DataSource),
		AuthInterceptor: middleware.NewAuthInterceptorMiddleware().Handle,
		Redis:           redisClient.Init(c),
	}
}

使用如下(可以不指定表名,通过结构体进行映射):

l.svcCtx.Redis.Set(req.Mobile, token.AccessToken, time.Second*60).Result()
total, _ := l.svcCtx.Engine.Table("user_basics").Where("mobile=?", req.Mobile).Count()

你可能感兴趣的:(golang,redis,开发语言)