PublishCode.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package models
  2. import (
  3. "PublishCode/conf"
  4. "PublishCode/lib"
  5. "PublishCode/logs"
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/astaxie/beego/cache"
  10. _ "github.com/astaxie/beego/cache/redis"
  11. _ "github.com/go-sql-driver/mysql"
  12. "go.mongodb.org/mongo-driver/bson"
  13. "go.mongodb.org/mongo-driver/bson/primitive"
  14. "go.mongodb.org/mongo-driver/mongo"
  15. "go.mongodb.org/mongo-driver/mongo/options"
  16. "strconv"
  17. "time"
  18. )
  19. // 模板
  20. type PublishCode_R struct {
  21. CodeNum string `bson:"CodeNum"`
  22. Data string `bson:"Data"`
  23. City Time `bson:"CreateTime"`
  24. }
  25. var redis_DeviceData cache.Cache
  26. var Mongodb_client *mongo.Client
  27. var Mongodb_DB *mongo.Database
  28. func init() {
  29. var err error
  30. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  31. "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  32. logs.Println(config)
  33. redis_DeviceData, err = cache.NewCache("redis", config)
  34. if err != nil || redis_DeviceData == nil {
  35. logs.PrintlnError(config, err)
  36. panic(any(err))
  37. }
  38. ConnectMongodb()
  39. }
  40. // 连接 Mongodb
  41. func ConnectMongodb() {
  42. credential := options.Credential{
  43. //AuthSource: conf.Mongodb_DB,
  44. Username: conf.Mongodb_Username,
  45. Password: conf.Mongodb_Password,
  46. AuthSource: conf.Mongodb_DB,
  47. }
  48. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
  49. defer cancel()
  50. var err error
  51. Mongodb_client, err = mongo.Connect(ctx, options.Client().ApplyURI(conf.Mongodb_Url).SetAuth(credential).SetMaxPoolSize(200))
  52. if err != nil {
  53. logs.PrintlnError("Mongodb 连接错误!", err)
  54. panic(any(err))
  55. } else {
  56. logs.Println("Mongodb OK!", conf.Mongodb_Url)
  57. }
  58. Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB)
  59. //测试连接
  60. logs.Println("Mongodb 测试连接!")
  61. collection := Mongodb_DB.Collection("yuniot")
  62. _, err = collection.InsertOne(context.TODO(), bson.D{{"time", time.Now()}})
  63. if err != nil {
  64. logs.Println("Mongodb:", conf.Mongodb_Url, conf.Mongodb_Username, conf.Mongodb_Password, conf.Mongodb_DB)
  65. logs.PrintlnError("Mongodb 连接测试错误!", err)
  66. panic(any(err))
  67. } else {
  68. logs.Println("Mongodb 测试连接 OK!")
  69. }
  70. }
  71. // ---------------- Redis -------------------
  72. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  73. func RedisDeviceData_Set(T_sn string, T_id int, r PublishCode_R) (err error) {
  74. key := T_sn + "|" + strconv.Itoa(T_id)
  75. if redis_DeviceData.IsExist(key) {
  76. var t PublishCode_R
  77. v := redis_DeviceData.Get(key)
  78. json.Unmarshal(v.([]byte), &t)
  79. // 防止时间溢出
  80. }
  81. //json序列化
  82. str, err := json.Marshal(r)
  83. if err != nil {
  84. logs.PrintlnError("RedisDeviceData_Set", err)
  85. return
  86. }
  87. err = redis_DeviceData.Put(key, str, 1*time.Hour)
  88. if err != nil {
  89. logs.Println("set key:", key, ",value:", str, err)
  90. }
  91. return
  92. }
  93. func RedisDeviceData_Get(key string) (r PublishCode_R, is bool) {
  94. if redis_DeviceData.IsExist(key) {
  95. v := redis_DeviceData.Get(key)
  96. json.Unmarshal(v.([]byte), &r)
  97. return r, true
  98. }
  99. return PublishCode_R{}, false
  100. }
  101. // ----------------
  102. func PublishCode_Add(JointTab string, bson_r *bson.M) error {
  103. //dd, _ := time.ParseDuration("8h")
  104. //(*bson_r)["CreateTime"] = time.Now().Add(dd) // 插入默认时间
  105. (*bson_r)["CreateTime"] = time.Now() // 插入默认时间
  106. //logs.Println("JointTab:", JointTab, *bson_r)
  107. //
  108. collection := Mongodb_DB.Collection(JointTab)
  109. _, err := collection.InsertOne(context.TODO(), bson_r)
  110. if err != nil {
  111. logs.PrintlnError("Data_Add:", err.Error())
  112. }
  113. return err
  114. }
  115. // ---------------- 索引
  116. func PublishCode_Indexes() {
  117. JointTab := lib.WeekByDate()
  118. //
  119. collection := Mongodb_DB.Collection(JointTab)
  120. // 创建索引
  121. _, err := collection.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
  122. Keys: bson.D{{"CodeNum", 1}}, // 设置索引字段和排序方式
  123. Options: options.Index().SetUnique(true), // 设置索引为唯一索引
  124. })
  125. if err != nil {
  126. logs.PrintlnError("Data_Add Indexes:", err.Error())
  127. }
  128. return
  129. }
  130. // db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0)
  131. // ----------------
  132. func CodeNum_Read(CodeNum string) (r map[string]interface{}, err error) {
  133. r = make(map[string]interface{})
  134. collection := Mongodb_DB.Collection(CodeNum[1:5])
  135. // 定义筛选条件
  136. filter := bson.D{{"CodeNum", CodeNum[5:]}}
  137. println(filter)
  138. // 执行查询操作
  139. var result bson.M
  140. err = collection.FindOne(context.Background(), filter).Decode(&result)
  141. r["CodeNum"] = CodeNum
  142. if err != nil {
  143. fmt.Println("Error finding document:", err)
  144. return
  145. }
  146. var articleSlide map[string]interface{}
  147. err = json.Unmarshal(result["Data"].(primitive.Binary).Data, &articleSlide)
  148. if err != nil {
  149. r["Data"] = lib.To_string(result["Data"])
  150. } else {
  151. r["Data"] = articleSlide
  152. }
  153. // 获取时间字段
  154. timeField := result["CreateTime"].(primitive.DateTime) / 1000
  155. timeValue := time.Unix(int64(timeField), 0)
  156. r["CreateTime"] = timeValue.Format("2006-01-02 15:04:05")
  157. fmt.Println("Found document:", r)
  158. return
  159. }