You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.2 KiB
63 lines
1.2 KiB
package data
|
|
|
|
import (
|
|
"customer/internal/biz"
|
|
"customer/internal/conf"
|
|
"fmt"
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"github.com/go-kratos/kratos/v2/log"
|
|
"github.com/google/wire"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// ProviderSet is data providers.
|
|
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewCusomerData)
|
|
|
|
// Data .
|
|
type Data struct {
|
|
Rdb *redis.Client
|
|
Mdb *gorm.DB
|
|
}
|
|
|
|
// NewData .
|
|
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
|
|
data := &Data{}
|
|
|
|
//初始化redis
|
|
redisURL := fmt.Sprintf("redis://%s/1?dial_timeout=%d", c.Redis.Addr, 1)
|
|
options, err := redis.ParseURL(redisURL)
|
|
if err != nil {
|
|
data.Rdb = nil
|
|
log.Fatal(err)
|
|
}
|
|
data.Rdb = redis.NewClient(options)
|
|
|
|
//初始化mysql
|
|
dsn := c.Database.Source
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
data.Mdb = nil
|
|
log.Fatal(err)
|
|
}
|
|
data.Mdb = db
|
|
|
|
cleanup := func() {
|
|
_ = data.Rdb.Close()
|
|
log.NewHelper(logger).Info("closing the data resources")
|
|
}
|
|
|
|
//初始化数据表
|
|
//migrateTable(db)
|
|
|
|
return data, cleanup, nil
|
|
}
|
|
|
|
func migrateTable(db *gorm.DB) {
|
|
if err := db.AutoMigrate(&biz.Customer{}); err != nil {
|
|
log.Info("customer table migrate error, err:", err)
|
|
}
|
|
}
|