ZBLOG

db.NfProfile.find() { "_id" : ObjectId("6787610fb3a57bc85615da74"), "nfType" : "AMF", "nfStatus" : "REGISTERED", "plmnList" : [ { "mcc" : "460", "mnc" : "01" } ], "ipv4Addresses" : [ "192.168.0.1" ], "nfInstanceId" : "NF_INSTANCE_ID_12345" } { "_i...

要将上述 MongoDB 中的文档结构存储到 Redis 中,你可以选择使用哈希表(Hash)来表示每个记录。每个记录的 _id 可以用作 Redis 键的一部分,哈希表中的字段则可以对应文档中的各个属性。

下面是一个示例,展示如何将这些记录转换并存储到 Redis 中,以及如何从 Redis 读取它们。

示例代码

假设你已经有 go-redismongo-go-driver 包安装,你可以按照以下方式进行操作:

1. 将数据从 MongoDB 存储到 Redis

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "github.com/go-redis/redis/v8"
  10. )
  11. type NfProfile struct {
  12. ID string `bson:"_id"`
  13. NfType string `bson:"nfType"`
  14. NfStatus string `bson:"nfStatus"`
  15. PmlnList []Plmn `bson:"plmnList"`
  16. Ipv4Addresses []string `bson:"ipv4Addresses"`
  17. NfInstanceId string `bson:"nfInstanceId"`
  18. }
  19. type Plmn struct {
  20. MCC string `bson:"mcc"`
  21. MNC string `bson:"mnc"`
  22. }
  23. func main() {
  24. ctx := context.Background()
  25. // MongoDB配置
  26. mongoClient, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
  27. if err != nil {
  28. log.Fatalf("Failed to connect to MongoDB: %v", err)
  29. }
  30. defer mongoClient.Disconnect(ctx)
  31. nfCollection := mongoClient.Database("your_database_name").Collection("NfProfile")
  32. cursor, err := nfCollection.Find(ctx, bson.D{})
  33. if err != nil {
  34. log.Fatalf("Failed to find documents: %v", err)
  35. }
  36. defer cursor.Close(ctx)
  37. rdb := redis.NewClient(&redis.Options{
  38. Addr: "localhost:6379",
  39. })
  40. defer rdb.Close()
  41. for cursor.Next(ctx) {
  42. var profile NfProfile
  43. if err := cursor.Decode(&profile); err != nil {
  44. log.Printf("Failed to decode document: %v", err)
  45. continue
  46. }
  47. key := fmt.Sprintf("nfprofile:%s", profile.ID) // 使用 _id 作为键前缀
  48. // 将数据存储为哈希表形式
  49. _, err = rdb.HSet(ctx, key,
  50. map[string]interface{}{
  51. "nfType": profile.NfType,
  52. "nfStatus": profile.NfStatus,
  53. "plmnList": profile.PmlnList,
  54. "ipv4Addresses": profile.Ipv4Addresses,
  55. "nfInstanceId": profile.NfInstanceId,
  56. }).Result()
  57. if err != nil {
  58. log.Printf("Error saving data to Redis: %v", err)
  59. }
  60. }
  61. if err := cursor.Err(); err != nil {
  62. log.Fatalf("Cursor error: %v", err)
  63. }
  64. fmt.Println("Data successfully migrated from MongoDB to Redis!")
  65. }

2. 从 Redis 获取特定类型的记录

在之前的示例中,你已经了解了如何根据特定条件查询Redis的数据。这次我们会针对你的数据结构做相应调整。

  1. func getRecordsByNfType(ctx context.Context, rdb *redis.Client, nfType string) ([]NfProfile, error) {
  2. keyPattern := "nfprofile:*" // 匹配所有键
  3. var profiles []NfProfile // 用于存储符合条件的记录
  4. iter := rdb.Scan(ctx, 0, keyPattern, 0).Iterator()
  5. for iter.Next(ctx) {
  6. key := iter.Val()
  7. recordData, err := rdb.HGetAll(ctx, key).Result()
  8. if err != nil || len(recordData) == 0 {
  9. continue
  10. }
  11. var profile NfProfile
  12. profile.ID = key[len("nfprofile:"):] // 去掉前缀以获取 ID
  13. // 手动将数据赋值给结构体属性
  14. if val, exists := recordData["nfType"]; exists {
  15. profile.NfType = val
  16. }
  17. if val, exists := recordData["nfStatus"]; exists {
  18. profile.NfStatus = val
  19. }
  20. // 提取其他字段...
  21. profiles = append(profiles, profile)
  22. }
  23. if iter.Err() != nil { return nil , iter.Err() }
  24. return profiles,nil
  25. }
  26. // 在主函数中调用查询方法并输出结果。

注意事项:

  1. MongoDB连接:确保在使用时替换数据库和集合名称。
  2. 错误处理:上面的代码简单处理了一些错误,实际应用中你可能需要更加详细的错误处理逻辑。
  3. 字段解析:此处为了简化解析过程,某些复杂对象(如嵌套数组或结构)未完全解析。需要根据实际情况编写 JSON 转换逻辑。
  4. Redis设计模式:对于高性能要求,可以考虑更复杂的数据模型,比如利用 Sorted Sets 或 Lists 来更有效地管理这些数据。

这样,你就完成了从 MongoDB 到 Redis 的迁移,并且能够根据条件检索所需的记录。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21138

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?