上篇文章讲到配置和日志已经初始化了,这篇文章接着把数据库和redis初始化完成。
数据库orm我选用xorm。首先在config.json和config.go添加对应的数据库配置。
config.json:
"db_config": {
"db_host": "127.0.0.1",
"db_port": "3306",
"db_user": "root",
"db_password": "123456",
"db_name": "test"
}
config.go
type DBConfig struct {
DbHost string `json:"db_host"`
DbPort string `json:"db_port"`
DbUser string `json:"db_user"`
DbPassword string `json:"db_password"`
DbName string `json:"db_name"`
}
接着,初始化数据库:
package db
import (
"github.com/TomatoMr/awesomeframework/config"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"github.com/pkg/errors"
)
var engine *xorm.Engine
func InitEngine() error {
var err error
conf := config.GetConfig()
engine, err = xorm.NewEngine("mysql", conf.DBConfig.DbUser+
":"+conf.DBConfig.DbPassword+"@tcp("+conf.DBConfig.DbHost+":"+conf.DBConfig.DbPort+")/"+conf.DBConfig.DbName+"?charset=utf8")
if err != nil {
err = errors.Wrap(err, "InitEngine1")
return err
}
err = engine.Ping()
if err != nil {
err = errors.Wrap(err, "InitEngine2")
return err
}
return nil
}
func GetEngine() *xorm.Engine {
return engine
}
我们再创建一个sql,等会测试连接用:
DROP DATABASE IF EXISTS `test`;
CREATE DATABASE `test`;
USE `test`;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`
(
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(40) NOT NULL COMMENT '名字',
`age` int NOT NULL DEFAULT 0 COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE = InnoDB COMMENT 'users';
同样先添加配置:
config.json:
"redis_config": {
"addr": "127.0.0.1:6379",
"password": "",
"db": 0
}
config.go:
type RedisConfig struct {
Addr string `json:"addr"`
Password string `json:"password"`
DB int `json:"db"`
}
初始化redis:
func InitRedis() error {
conf := config.GetConfig()
client = redis.NewClient(&redis.Options{
Addr: conf.RedisConfig.Addr,
Password: conf.RedisConfig.Password,
DB: conf.RedisConfig.DB,
})
pong, err := client.Ping().Result()
if err != nil {
err = errors.Wrap(err, "InitRedis")
return err
}
logger.GetLogger().Info("Redis ping:", zap.String("ping", pong))
return nil
}
err = db.InitEngine()
if err != nil {
fmt.Printf("Init DB failed. Error is %v", err)
os.Exit(1)
}
err = redis.InitRedis()
if err != nil {
fmt.Printf("Init Redis failed. Error is %v", err)
os.Exit(1)
}
使用上面的sql,创建一个数据库叫做test,然后搭建redis,接着我们测试一下:
编译:
go build
运行:
awesomeframework --config=./config/config.json
看下日志打印:
2020-01-20T20:09:26.798+0800 info Redis ping: {"ping": "PONG"}
2020-01-20T20:09:26.798+0800 info Init success.
这篇文章写了数据库和redis的初始化,可以在https://github.com/TomatoMr/awesomeframework找到今天的代码。未完待续……
欢迎关注我的公众号:onepunchgo,给我留言。