package models import ( "PublishCode/conf" "PublishCode/lib" "PublishCode/logs" "context" "encoding/json" "fmt" "github.com/astaxie/beego/cache" _ "github.com/astaxie/beego/cache/redis" _ "github.com/go-sql-driver/mysql" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "strconv" "time" ) // 模板 type PublishCode_R struct { CodeNum string `bson:"CodeNum"` Data string `bson:"Data"` City Time `bson:"CreateTime"` } var redis_DeviceData cache.Cache var Mongodb_client *mongo.Client var Mongodb_DB *mongo.Database func init() { var err error config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`, "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password) logs.Println(config) redis_DeviceData, err = cache.NewCache("redis", config) if err != nil || redis_DeviceData == nil { logs.PrintlnError(config, err) panic(any(err)) } ConnectMongodb() } // 连接 Mongodb func ConnectMongodb() { credential := options.Credential{ //AuthSource: conf.Mongodb_DB, Username: conf.Mongodb_Username, Password: conf.Mongodb_Password, AuthSource: conf.Mongodb_DB, } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() var err error Mongodb_client, err = mongo.Connect(ctx, options.Client().ApplyURI(conf.Mongodb_Url).SetAuth(credential).SetMaxPoolSize(200)) if err != nil { logs.PrintlnError("Mongodb 连接错误!", err) panic(any(err)) } else { logs.Println("Mongodb OK!", conf.Mongodb_Url) } Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB) //测试连接 logs.Println("Mongodb 测试连接!") collection := Mongodb_DB.Collection("yuniot") _, err = collection.InsertOne(context.TODO(), bson.D{{"time", time.Now()}}) if err != nil { logs.Println("Mongodb:", conf.Mongodb_Url, conf.Mongodb_Username, conf.Mongodb_Password, conf.Mongodb_DB) logs.PrintlnError("Mongodb 连接测试错误!", err) panic(any(err)) } else { logs.Println("Mongodb 测试连接 OK!") } } // ---------------- Redis ------------------- // Redis_Set(m.T_sn,m) // Redis 更新缓存 func RedisDeviceData_Set(T_sn string, T_id int, r PublishCode_R) (err error) { key := T_sn + "|" + strconv.Itoa(T_id) if redis_DeviceData.IsExist(key) { var t PublishCode_R v := redis_DeviceData.Get(key) json.Unmarshal(v.([]byte), &t) // 防止时间溢出 } //json序列化 str, err := json.Marshal(r) if err != nil { logs.PrintlnError("RedisDeviceData_Set", err) return } err = redis_DeviceData.Put(key, str, 1*time.Hour) if err != nil { logs.Println("set key:", key, ",value:", str, err) } return } func RedisDeviceData_Get(key string) (r PublishCode_R, is bool) { if redis_DeviceData.IsExist(key) { v := redis_DeviceData.Get(key) json.Unmarshal(v.([]byte), &r) return r, true } return PublishCode_R{}, false } // ---------------- func PublishCode_Add(JointTab string, bson_r *bson.M) error { //dd, _ := time.ParseDuration("8h") //(*bson_r)["CreateTime"] = time.Now().Add(dd) // 插入默认时间 (*bson_r)["CreateTime"] = time.Now() // 插入默认时间 //logs.Println("JointTab:", JointTab, *bson_r) // collection := Mongodb_DB.Collection(JointTab) _, err := collection.InsertOne(context.TODO(), bson_r) if err != nil { logs.PrintlnError("Data_Add:", err.Error()) } return err } // ---------------- 索引 func PublishCode_Indexes() { JointTab := lib.WeekByDate() // collection := Mongodb_DB.Collection(JointTab) // 创建索引 _, err := collection.Indexes().CreateOne(context.TODO(), mongo.IndexModel{ Keys: bson.D{{"CodeNum", 1}}, // 设置索引字段和排序方式 Options: options.Index().SetUnique(true), // 设置索引为唯一索引 }) if err != nil { logs.PrintlnError("Data_Add Indexes:", err.Error()) } return } // db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0) // ---------------- func CodeNum_Read(CodeNum string) (r map[string]interface{}, err error) { r = make(map[string]interface{}) collection := Mongodb_DB.Collection(CodeNum[1:5]) // 定义筛选条件 filter := bson.D{{"CodeNum", CodeNum[5:]}} println(filter) // 执行查询操作 var result bson.M err = collection.FindOne(context.Background(), filter).Decode(&result) r["CodeNum"] = CodeNum if err != nil { fmt.Println("Error finding document:", err) return } var articleSlide map[string]interface{} err = json.Unmarshal(result["Data"].(primitive.Binary).Data, &articleSlide) if err != nil { r["Data"] = lib.To_string(result["Data"]) } else { r["Data"] = articleSlide } // 获取时间字段 timeField := result["CreateTime"].(primitive.DateTime) / 1000 timeValue := time.Unix(int64(timeField), 0) r["CreateTime"] = timeValue.Format("2006-01-02 15:04:05") fmt.Println("Found document:", r) return }