temp
This commit is contained in:
29
Server/common/db/etcd/etcd.go
Normal file
29
Server/common/db/etcd/etcd.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package etcd
|
||||
|
||||
import (
|
||||
commonConfig "common/config"
|
||||
"fmt"
|
||||
clientv3 "go.etcd.io/etcd/client/v3"
|
||||
)
|
||||
|
||||
var etcdClient *clientv3.Client
|
||||
|
||||
func Init(cfg *commonConfig.EtcdConfig) error {
|
||||
client, err := clientv3.New(clientv3.Config{
|
||||
Endpoints: []string{fmt.Sprintf("%v:%v", cfg.Host, cfg.Port)},
|
||||
DialTimeout: 0,
|
||||
})
|
||||
etcdClient = client
|
||||
return err
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
if etcdClient != nil {
|
||||
return etcdClient.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Client() *clientv3.Client {
|
||||
return etcdClient
|
||||
}
|
||||
77
Server/common/db/mongo/mongo.go
Normal file
77
Server/common/db/mongo/mongo.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
commonConfig "common/config"
|
||||
"common/log"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"go.mongodb.org/mongo-driver/event"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
var (
|
||||
MDB *mongo.Client
|
||||
DefaultDB *mongo.Database
|
||||
ChatDB *mongo.Database
|
||||
ErrNoDocuments = mongo.ErrNoDocuments
|
||||
)
|
||||
|
||||
func Init(cfg *commonConfig.MongoConfig) error {
|
||||
dialect := ""
|
||||
if len(cfg.User) > 0 && len(cfg.Password) > 0 {
|
||||
dialect = fmt.Sprintf("mongodb://%s:%s@%s:%d/admin?appname=MongoDB", cfg.User, cfg.Password, cfg.Host, cfg.Port)
|
||||
} else {
|
||||
dialect = fmt.Sprintf("mongodb://%s:%d/admin?readPreference=primary&appname=MongoDB&ssl=false", cfg.Host, cfg.Port)
|
||||
}
|
||||
var clientOptions *options.ClientOptions
|
||||
if len(cfg.SSLCaFile) > 0 {
|
||||
data, err := ioutil.ReadFile(cfg.SSLCaFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dialect += "&ssl=true"
|
||||
roots := x509.NewCertPool()
|
||||
roots.AppendCertsFromPEM(data)
|
||||
clientOptions = options.Client().ApplyURI(dialect).SetTLSConfig(&tls.Config{
|
||||
RootCAs: roots,
|
||||
//InsecureSkipVerify: true,
|
||||
}).SetRetryWrites(false)
|
||||
} else {
|
||||
dialect += "&ssl=false"
|
||||
clientOptions = options.Client().ApplyURI(dialect).SetRetryWrites(false)
|
||||
}
|
||||
monitor := &event.CommandMonitor{
|
||||
Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
|
||||
log.Infof("mongoDB Command started %v %v", startedEvent.CommandName, startedEvent.Command.String())
|
||||
},
|
||||
Failed: func(ctx context.Context, failedEvent *event.CommandFailedEvent) {
|
||||
log.Errorf("mongoDB Command error %v %v", failedEvent.CommandName, failedEvent.Failure)
|
||||
},
|
||||
}
|
||||
clientOptions.SetMonitor(monitor)
|
||||
client, err := mongo.Connect(context.Background(), clientOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.Ping(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
MDB = client
|
||||
DefaultDB = MDB.Database("ecosmos")
|
||||
ChatDB = MDB.Database("ecosmos_chat")
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
if MDB != nil {
|
||||
return MDB.Disconnect(context.Background())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
90
Server/common/db/mysql/mysql.go
Normal file
90
Server/common/db/mysql/mysql.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
commonConfig "common/config"
|
||||
"common/log"
|
||||
"common/query"
|
||||
|
||||
"fmt"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DBNameEcosmos = "ecosmos"
|
||||
DBNameEcosmosShop = "ecosmos_shop"
|
||||
)
|
||||
|
||||
var dbs = make(map[string]*gorm.DB)
|
||||
var queryS = make(map[string]*query.Query)
|
||||
|
||||
func Init(cfg *commonConfig.MysqlConfig) error {
|
||||
db, err := initOneDB(cfg, DBNameEcosmosShop)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
queryS[DBNameEcosmosShop] = query.Use(db)
|
||||
|
||||
db, err = initOneDB(cfg, DBNameEcosmos)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query.SetDefault(db)
|
||||
queryS[DBNameEcosmos] = query.Q
|
||||
return nil
|
||||
}
|
||||
|
||||
func initOneDB(cfg *commonConfig.MysqlConfig, dbName string) (*gorm.DB, error) {
|
||||
dialect := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.User, cfg.Password, cfg.Host, cfg.Port, dbName)
|
||||
db, err := gorm.Open(
|
||||
mysql.New(
|
||||
mysql.Config{
|
||||
DSN: dialect,
|
||||
},
|
||||
),
|
||||
&gorm.Config{
|
||||
TranslateError: true,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDb, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sqlDb.SetMaxOpenConns(50)
|
||||
sqlDb.SetMaxIdleConns(5)
|
||||
sqlDb.SetConnMaxLifetime(time.Second * 10)
|
||||
if err = sqlDb.Ping(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dbs[dbName] = db
|
||||
return db.Debug(), nil
|
||||
}
|
||||
|
||||
func DBQuery(dbName string) *query.Query {
|
||||
if q, ok := queryS[dbName]; ok {
|
||||
return q
|
||||
}
|
||||
|
||||
log.Errorf("mysql db not init: %v", dbName)
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
fmt.Println("close mysql connect")
|
||||
for _, db := range dbs {
|
||||
sqlDb, err := db.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = sqlDb.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
24
Server/common/db/mysql/sql_code/const.go
Normal file
24
Server/common/db/mysql/sql_code/const.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package sql_code
|
||||
|
||||
const (
|
||||
Unread_HasRead = 1
|
||||
Unread_NotRead = 0
|
||||
IsAgree_Agree = 1
|
||||
IsAgree_Refuse = -1
|
||||
IsAgree_NoDeal = 0
|
||||
Online = 1
|
||||
Offline = 0
|
||||
Mail_UN_READ = 0
|
||||
|
||||
MAIL_UN_READ = 0
|
||||
|
||||
MAIL_READ_NOT_GET = 1
|
||||
|
||||
MAIL_READ_HAS_GET = 2
|
||||
|
||||
MAIL_HAS_DELETE = 3
|
||||
|
||||
MAIL_NO_EXTRAL = 0
|
||||
|
||||
MAIL_HAS_EXTRAL = 1
|
||||
)
|
||||
57
Server/common/db/redis/redisV9.go
Normal file
57
Server/common/db/redis/redisV9.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
commonConfig "common/config"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
redisClient *redis.Client
|
||||
redisNotInitErr = errors.New("redis is not initialized.")
|
||||
keyNotExist = errors.New("key does not exist")
|
||||
Nil = redis.Nil
|
||||
)
|
||||
|
||||
func Init(cfg *commonConfig.RedisConfig) error {
|
||||
url := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
|
||||
if cfg.Tls {
|
||||
redisClient = redis.NewClient(&redis.Options{
|
||||
Addr: url,
|
||||
Password: cfg.Auth,
|
||||
DB: cfg.Db,
|
||||
DialTimeout: 20 * time.Second,
|
||||
Username: cfg.UserName,
|
||||
TLSConfig: &tls.Config{},
|
||||
})
|
||||
} else {
|
||||
redisClient = redis.NewClient(&redis.Options{
|
||||
Addr: url,
|
||||
Password: cfg.Auth,
|
||||
DB: cfg.Db,
|
||||
DialTimeout: 20 * time.Second,
|
||||
})
|
||||
}
|
||||
|
||||
ret := redisClient.Ping(context.Background())
|
||||
//p := redisClient.Pipeline()
|
||||
//l := p.HGetAll(xxx, xxx)
|
||||
//s := p.Get(xxx, xx)
|
||||
//p.Exec(xxx)
|
||||
return ret.Err()
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
if redisClient != nil {
|
||||
return redisClient.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetRedisClient() *redis.Client {
|
||||
return redisClient
|
||||
}
|
||||
37
Server/common/db/redis/redis_lock.go
Normal file
37
Server/common/db/redis/redis_lock.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"common/log"
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ReleaseLockExpire = errors.New("release redis lock expire key")
|
||||
|
||||
func Acquire(ctx context.Context, key string, tag string, expiration time.Duration) (bool, error) {
|
||||
success, err := redisClient.SetNX(ctx, key, tag, expiration).Result()
|
||||
return success, err
|
||||
}
|
||||
|
||||
func Release(ctx context.Context, key string, tag string) error {
|
||||
script := `
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end`
|
||||
|
||||
// 执行 Lua 脚本
|
||||
result, err := redisClient.Eval(ctx, script, []string{key}, tag).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 检查返回值
|
||||
if result == int64(0) {
|
||||
log.Errorf("release redis lock expire key :%v", key)
|
||||
return ReleaseLockExpire
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
49
Server/common/db/test_db.go
Normal file
49
Server/common/db/test_db.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"common/config"
|
||||
"common/db/mongo"
|
||||
"common/db/mysql"
|
||||
"common/log"
|
||||
"common/utils"
|
||||
"fmt"
|
||||
"github.com/jinzhu/configor"
|
||||
"math/rand"
|
||||
"os"
|
||||
)
|
||||
|
||||
// 用于单元测试初始化数据库
|
||||
|
||||
func InitTestDB(env string) {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
fmt.Println("无法获取工作目录:", err)
|
||||
return
|
||||
}
|
||||
|
||||
var commonCfg config.CommonConfig
|
||||
err = configor.Load(&commonCfg, fmt.Sprintf(wd+"/config/common-config-%v.json", env))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
log.Init(&commonCfg.Logger)
|
||||
utils.InitSnowflake(int64(rand.Intn(1000)))
|
||||
//// Redis
|
||||
//if err := redis.Init(&commonCfg.Redis); err != nil {
|
||||
// panic(err)
|
||||
//}
|
||||
// MySQL
|
||||
if err := mysql.Init(&commonCfg.MysqlConfig); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Mongo
|
||||
if err := mongo.Init(&commonCfg.MongoConfig); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
//// Etcd
|
||||
//if err := etcd.Init(&commonCfg.Etcd); err != nil {
|
||||
// panic(err)
|
||||
//}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user