Files
open-im-server/pkg/common/db/model.go
T

201 lines
7.1 KiB
Go
Raw Normal View History

2021-05-26 19:17:51 +08:00
package db
import (
"Open_IM/pkg/common/config"
2022-07-08 19:26:44 +08:00
"github.com/dtm-labs/rockscache"
2022-05-06 17:23:37 +08:00
"go.mongodb.org/mongo-driver/x/bsonx"
"strings"
2022-04-05 19:31:35 +08:00
//"Open_IM/pkg/common/log"
2022-02-23 12:27:01 +08:00
"Open_IM/pkg/utils"
"fmt"
2022-05-31 11:47:35 +08:00
go_redis "github.com/go-redis/redis/v8"
2022-02-23 12:27:01 +08:00
"go.mongodb.org/mongo-driver/mongo/options"
2022-06-15 16:35:24 +08:00
2021-05-26 19:17:51 +08:00
"gopkg.in/mgo.v2"
2021-06-28 15:32:26 +08:00
"time"
2022-02-21 15:01:06 +08:00
2022-02-23 12:27:01 +08:00
"context"
2022-02-21 15:01:06 +08:00
//"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
2022-02-23 12:00:02 +08:00
// "go.mongodb.org/mongo-driver/mongo/options"
2022-05-26 12:10:45 +08:00
//go_redis "github.com/go-redis/redis/v8"
2021-05-26 19:17:51 +08:00
)
var DB DataBases
type DataBases struct {
2022-06-15 16:35:24 +08:00
MysqlDB mysqlDB
mgoSession *mgo.Session
//redisPool *redis.Pool
2022-02-21 15:01:06 +08:00
mongoClient *mongo.Client
2022-07-20 11:35:19 +08:00
RDB go_redis.UniversalClient
2022-07-08 19:26:44 +08:00
Rc *rockscache.Client
2022-07-19 16:15:23 +08:00
WeakRc *rockscache.Client
2022-06-16 14:45:39 +08:00
}
type RedisClient struct {
client *go_redis.Client
cluster *go_redis.ClusterClient
go_redis.UniversalClient
2021-05-26 19:17:51 +08:00
}
func key(dbAddress, dbName string) string {
return dbAddress + "_" + dbName
}
func init() {
2022-04-05 19:31:35 +08:00
//log.NewPrivateLog(constant.LogFileName)
2022-02-21 15:01:06 +08:00
var mongoClient *mongo.Client
2021-11-26 14:34:00 +08:00
var err1 error
2021-06-28 15:32:26 +08:00
//mysql init
2021-07-15 11:14:07 +08:00
initMysqlDB()
2021-11-11 19:04:35 +08:00
// mongo init
2022-02-21 15:01:06 +08:00
// "mongodb://sysop:moon@localhost/records"
2022-02-23 14:30:21 +08:00
uri := "mongodb://sample.host:27017/?maxPoolSize=20&w=majority"
2022-03-21 11:13:17 +08:00
if config.Config.Mongo.DBUri != "" {
// example: mongodb://$user:$password@mongo1.mongo:27017,mongo2.mongo:27017,mongo3.mongo:27017/$DBDatabase/?replicaSet=rs0&readPreference=secondary&authSource=admin&maxPoolSize=$DBMaxPoolSize
uri = config.Config.Mongo.DBUri
} else {
2022-04-15 11:56:36 +08:00
if config.Config.Mongo.DBPassword != "" && config.Config.Mongo.DBUserName != "" {
2022-06-17 10:50:15 +08:00
uri = fmt.Sprintf("mongodb://%s:%s@%s/%s?maxPoolSize=%d", config.Config.Mongo.DBUserName, config.Config.Mongo.DBPassword, config.Config.Mongo.DBAddress,
2022-04-15 11:56:36 +08:00
config.Config.Mongo.DBDatabase, config.Config.Mongo.DBMaxPoolSize)
2022-04-15 17:43:04 +08:00
} else {
uri = fmt.Sprintf("mongodb://%s/%s/?maxPoolSize=%d",
2022-06-17 10:50:15 +08:00
config.Config.Mongo.DBAddress, config.Config.Mongo.DBDatabase,
2022-04-15 17:43:04 +08:00
config.Config.Mongo.DBMaxPoolSize)
2022-04-15 11:56:36 +08:00
}
2022-03-21 11:13:17 +08:00
}
2022-02-23 12:27:01 +08:00
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
2022-03-31 11:28:51 +08:00
if err != nil {
2022-04-05 19:31:35 +08:00
fmt.Println(" mongo.Connect failed, try ", utils.GetSelfFuncName(), err.Error(), uri)
2022-02-23 12:27:01 +08:00
time.Sleep(time.Duration(30) * time.Second)
mongoClient, err1 = mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err1 != nil {
2022-04-05 19:31:35 +08:00
fmt.Println(" mongo.Connect retry failed, panic", err.Error(), uri)
2022-02-23 12:27:01 +08:00
panic(err1.Error())
}
}
2022-04-15 17:43:04 +08:00
fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success: ", uri)
2022-04-18 19:24:36 +08:00
// mongodb create index
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cSendLog, false, "send_id", "-send_time"); err != nil {
fmt.Println("send_id", "-send_time", "index create failed", err.Error())
2022-05-06 17:23:37 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cChat, true, "uid"); err != nil {
fmt.Println("uid", " index create failed", err.Error())
2022-04-18 19:24:36 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cWorkMoment, true, "-create_time", "work_moment_id"); err != nil {
fmt.Println("-create_time", "work_moment_id", "index create failed", err.Error())
2022-04-18 19:24:36 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cWorkMoment, true, "work_moment_id"); err != nil {
fmt.Println("work_moment_id", "index create failed", err.Error())
2022-05-06 15:58:50 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cWorkMoment, false, "user_id", "-create_time"); err != nil {
fmt.Println("user_id", "-create_time", "index create failed", err.Error())
2022-04-18 19:24:36 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cTag, false, "user_id", "-create_time"); err != nil {
fmt.Println("user_id", "-create_time", "index create failed", err.Error())
2022-05-06 15:58:50 +08:00
}
2022-05-06 17:32:52 +08:00
if err := createMongoIndex(mongoClient, cTag, true, "tag_id"); err != nil {
2022-07-14 12:08:28 +08:00
fmt.Println("tag_id", "index create failed", err.Error())
2022-04-18 19:24:36 +08:00
}
2022-05-06 17:35:33 +08:00
fmt.Println("create index success")
2022-04-18 19:24:36 +08:00
DB.mongoClient = mongoClient
2022-02-21 15:01:06 +08:00
2021-06-28 15:32:26 +08:00
// redis pool init
2022-06-15 16:35:24 +08:00
//DB.redisPool = &redis.Pool{
// MaxIdle: config.Config.Redis.DBMaxIdle,
// MaxActive: config.Config.Redis.DBMaxActive,
// IdleTimeout: time.Duration(config.Config.Redis.DBIdleTimeout) * time.Second,
// Dial: func() (redis.Conn, error) {
// return redis.Dial(
// "tcp",
// config.Config.Redis.DBAddress,
// redis.DialReadTimeout(time.Duration(1000)*time.Millisecond),
// redis.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
// redis.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
// redis.DialDatabase(0),
// redis.DialPassword(config.Config.Redis.DBPassWord),
// )
// },
//}
2022-07-08 16:34:23 +08:00
fmt.Println("tes", config.Config.Redis.DBUserName, config.Config.Redis.DBPassWord)
2022-05-31 11:47:35 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
2022-06-16 14:45:39 +08:00
if config.Config.Redis.EnableCluster {
2022-07-20 11:35:19 +08:00
DB.RDB = go_redis.NewClusterClient(&go_redis.ClusterOptions{
2022-06-17 10:50:15 +08:00
Addrs: config.Config.Redis.DBAddress,
2022-07-08 16:22:52 +08:00
Username: config.Config.Redis.DBUserName,
2022-07-08 15:17:46 +08:00
Password: config.Config.Redis.DBPassWord, // no password set
2022-06-16 14:45:39 +08:00
PoolSize: 50,
})
2022-07-20 11:35:19 +08:00
_, err = DB.RDB.Ping(ctx).Result()
2022-06-16 14:45:39 +08:00
if err != nil {
panic(err.Error())
}
} else {
2022-07-20 11:35:19 +08:00
DB.RDB = go_redis.NewClient(&go_redis.Options{
2022-06-17 10:50:15 +08:00
Addr: config.Config.Redis.DBAddress[0],
2022-07-08 15:17:46 +08:00
Username: config.Config.Redis.DBUserName,
2022-06-16 14:45:39 +08:00
Password: config.Config.Redis.DBPassWord, // no password set
DB: 0, // use default DB
PoolSize: 100, // 连接池大小
})
2022-07-20 11:35:19 +08:00
_, err = DB.RDB.Ping(ctx).Result()
2022-06-16 14:45:39 +08:00
if err != nil {
panic(err.Error())
}
2022-05-31 11:47:35 +08:00
}
2022-07-19 16:15:23 +08:00
// 强一致性缓存,当一个key被标记删除,其他请求线程会被锁住轮询直到新的key生成,适合各种同步的拉取, 如果弱一致可能导致拉取还是老数据,毫无意义
2022-07-14 12:08:28 +08:00
DB.Rc = rockscache.NewClient(go_redis.NewClient(&go_redis.Options{
2022-07-08 19:26:44 +08:00
Addr: config.Config.Redis.DBAddress[0],
Password: config.Config.Redis.DBPassWord, // no password set
DB: 0, // use default DB
PoolSize: 100, // 连接池大小
}), rockscache.NewDefaultOptions())
2022-07-19 16:15:23 +08:00
DB.Rc.Options.StrongConsistency = true
// 弱一致性缓存,当一个key被标记删除,其他请求线程直接返回该key的value,适合高频并且生成很缓存很慢的情况 如大群发消息缓存的缓存
DB.WeakRc = rockscache.NewClient(go_redis.NewClient(&go_redis.Options{
Addr: config.Config.Redis.DBAddress[0],
Password: config.Config.Redis.DBPassWord, // no password set
DB: 0, // use default DB
PoolSize: 100, // 连接池大小
}), rockscache.NewDefaultOptions())
DB.WeakRc.Options.StrongConsistency = false
2021-05-26 19:17:51 +08:00
}
2022-05-06 17:23:37 +08:00
2022-05-06 17:32:52 +08:00
func createMongoIndex(client *mongo.Client, collection string, isUnique bool, keys ...string) error {
2022-05-06 17:23:37 +08:00
db := client.Database(config.Config.Mongo.DBDatabase).Collection(collection)
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
indexView := db.Indexes()
keysDoc := bsonx.Doc{}
// 复合索引
for _, key := range keys {
if strings.HasPrefix(key, "-") {
keysDoc = keysDoc.Append(strings.TrimLeft(key, "-"), bsonx.Int32(-1))
} else {
keysDoc = keysDoc.Append(key, bsonx.Int32(1))
}
}
// 创建索引
index := mongo.IndexModel{
Keys: keysDoc,
}
if isUnique == true {
index.Options = options.Index().SetUnique(true)
}
result, err := indexView.CreateOne(
context.Background(),
index,
opts,
)
if err != nil {
return utils.Wrap(err, result)
}
return nil
}