基于GO的即时聊天后端项目(二)项目初始化工作

本文详细描述了如何在项目中配置MySQL连接池,使用Gorm库,以及设置Zap日志库用于高性能日志记录,同时介绍了如何初始化Redis数据库以存储用户数据,包括日志配置和连接管理。
摘要由CSDN通过智能技术生成


配置MySQL连接池

  • 在 /gobal/gobal.go 中声明全局连接池变量
import (
	"gorm.io/gorm"
)

var DB *gorm.DB
  • 在 /initialize/db.go 中的 InitDB() 函数中声明连接语句
// declare the connection to the DB
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.User, config.Password, config.Host, config.Port, config.DBName)
  • 接着设置数据库的日志配置
// set the config of logger
	newLogger := logger.New(
		// writer
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		// config
		logger.Config{
			// set the threshold of slow query, and the query cost more than 1s will be record
			SlowThreshold: time.Second,
			// print different kind of information by different color
			Colorful: true,
			// ignore the error that didn't exist the record
			IgnoreRecordNotFoundError: true,
			// we record all kind of log, can set as Silent->Error->Warn->Info
			LogLevel: logger.Info,
		},
	)
  • 最后执行连接,完成数据库初始化
// connect to DB
	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}    

Zap日志配置

Zap是一种高性能日志库,提供结构化分级的日志记录功能

  • 在 /initialize/logger.go中初始化ZAP的日志配置
import (
	"go.uber.org/zap"
	"log"
)

func InitLogger() {
	logger, err := zap.NewDevelopment()
	if err != nil {
		log.Fatal("Logger Initial Failed", err.Error())
	}
	// set Zap can be called globally
	zap.ReplaceGlobals(logger)
}

Redis初始化

Redis 是一个高性能的 key-value 数据库,在项目中可用于存储用户的聊天记录。在本项目中,我们通过 go-redis库 对 Redis 进行操作

  • 在 /gobal/gobal.go 中声明全局连接池变量
import (
	"github.com/redis/go-redis/v9"
)

var RedisDB *redis.Client
  • 在 /initialize/db.go 中进行 Redis 初始化
import "github.com/redis/go-redis/v9"

// InitRedis initial the connection to the Redis DB
func InitRedis() {
	redisConfig := global.ServiceConfig.RedisDB
	opt := redis.Options{
		Addr:     fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port),
		Password: redisConfig.Password,
		DB:       redisConfig.DB,
	}
	global.RedisDB = redis.NewClient(&opt)
}

完成初始化

  • 在main中调用三个初始化函数以完成初始化:
func main() {
	initialize.InitLogger()
	initialize.InitDB()
	initialize.InitRedis()
	println("successfully initialize!")
}
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值