2023-01-06 10:09:23 +08:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"hpds-iot-web/config"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
"xorm.io/xorm"
|
|
|
|
"xorm.io/xorm/dialects"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
DB *xorm.Engine
|
|
|
|
Redis *redis.Client
|
|
|
|
)
|
|
|
|
|
|
|
|
func New(driveName, dsn string) {
|
|
|
|
DB, _ = NewDbConnection(dsn)
|
|
|
|
DB.ShowSQL(true)
|
|
|
|
DB.Dialect().SetQuotePolicy(dialects.QuotePolicyReserved)
|
|
|
|
err := DB.Sync2(
|
|
|
|
&Brand{},
|
|
|
|
&DetectionTask{},
|
|
|
|
&Device{},
|
|
|
|
&DeviceType{},
|
|
|
|
&Disease{},
|
|
|
|
&MatterAttribute{},
|
|
|
|
&MatterCategory{},
|
|
|
|
&MatterEvent{},
|
|
|
|
&MatterEventParams{},
|
|
|
|
&MatterModel{},
|
|
|
|
&MatterService{},
|
|
|
|
&MatterServiceParams{},
|
|
|
|
&MatterVersion{},
|
2023-01-06 16:10:18 +08:00
|
|
|
&Model{},
|
|
|
|
&ModelVersion{},
|
2023-01-06 10:09:23 +08:00
|
|
|
&Node{},
|
|
|
|
&OriginalData{},
|
|
|
|
&Owner{},
|
|
|
|
&Project{},
|
|
|
|
&SystemMenu{},
|
|
|
|
&OperationLog{},
|
|
|
|
&SystemRoleMenu{},
|
|
|
|
&SystemRoleRoute{},
|
|
|
|
&SystemRole{},
|
|
|
|
&SystemUser{},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
zap.L().Error("同步数据库表结构", zap.Error(err))
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDbConnection(dsn string) (db *xorm.Engine, err error) {
|
|
|
|
db, err = xorm.NewEngine("mysql", dsn)
|
|
|
|
if err != nil {
|
|
|
|
zap.L().Error("创建数据库连接", zap.Error(err))
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
db.SetMaxOpenConns(300)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCache(c config.CacheConfig) {
|
|
|
|
Redis = redis.NewClient(&redis.Options{
|
|
|
|
Addr: fmt.Sprintf("%s:%d", c.Host, c.Port),
|
|
|
|
Password: c.Pass, // no password set
|
|
|
|
DB: c.DB, // use default DB
|
|
|
|
PoolSize: c.PoolSize, // Redis连接池大小
|
|
|
|
MaxRetries: 3, // 最大重试次数
|
|
|
|
IdleTimeout: 10 * time.Second, // 空闲链接超时时间
|
|
|
|
})
|
|
|
|
pong, err := Redis.Ping().Result()
|
|
|
|
if err == redis.Nil {
|
|
|
|
zap.L().Error("访问Redis异常", zap.Error(fmt.Errorf("redis.Nil")))
|
|
|
|
} else if err != nil {
|
|
|
|
zap.L().Error("访问Redis异常", zap.Error(err))
|
|
|
|
} else {
|
|
|
|
zap.L().Info("Redis连接成功", zap.String("pong", pong))
|
|
|
|
}
|
|
|
|
}
|