ch3-使用MongoDB数据持久化--使用go-gin创建分布式应用

本文介绍了如何在Go Gin应用中使用MongoDB进行数据持久化,并实现了CRUD操作。同时,文章讨论了如何结合Redis进行数据缓存,以提升API性能。通过docker部署MongoDB和Redis,详细讲解了数据库连接、数据模型、路由处理和缓存策略。最后,进行了网站性能跑分测试。
摘要由CSDN通过智能技术生成

系列文章目录

第一章 gin初步认识
第二章 设置API
第三章 使用MongoDB数据持久化



在这里插入图片描述


注:

  1. 系列文章是对应上述英文原版书的学习笔记
  2. 相关自己的练习代码包含注释,放在在本人的gitee,欢迎star
  3. 所有内容允许转载,如果侵犯书籍的著作权益,请联系删除
  4. 笔记持续更新中

使用MongoDB数据持久化

前言

本章将会用docker部署MongoDB和Redis,实现CRUD,介绍标准go项目目录结构,优化API响应提高网站性能

go使用mongodb

  1. 在项目中获取依赖

go get go.mongodb.org/mongo-driver/mongo

这将会下载驱动到系统GOPath,并把其作为依赖写入go.mod文件中

  1. 连接MongoDB
  • docker运行mongodb

docker run -d --name mongodb -e MONGO_INITDB_ROOT_ USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=password -p 27017:27017 mongo:4.4.3

  • 使用免费的mongo atlas数据库
  • 数据库的连接和测试代码
package main

import (
   "context"
   "fmt"
   "go.mongodb.org/mongo-driver/mongo"
   "go.mongodb.org/mongo-driver/mongo/options"
   "go.mongodb.org/mongo-driver/mongo/readpref"
   "log"
)

var ctx context.Context
var err error
var client *mongo.Client

// 使用环境变量定义的数据库地址
//var uri = os.Getenv("MONGO_URI")
var uri = "***********************************************************"

func init() {
   
   ctx = context.Background()
   client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri))
   if err = client.Ping(context.TODO(), readpref.Primary()); err != nil {
   
      log.Fatal(err)
   }
   fmt.Println("Connected to MongoDB")
}
func main() {
   
   
}
  1. 使用上一章的数据初始化数据库
func init() {
   
   recipes = make([]model.Recipe, 0)
   // 读取文件中的信息
   file, _ := ioutil.ReadFile("recipes.json")
   // 把信息解析为recipe实体
   _ = json.Unmarshal([]byte(file), &recipes)

   ...

   // InsertMany传递的数据参数就是interface
   var listOfRecipes []interface{
   }
   for _, recipe := range recipes {
   
      listOfRecipes = append(listOfRecipes, recipe)
   }
   collection := client.Database(database_name).Collection(collection_name)
   insertManyResult, err := collection.InsertMany(ctx, listOfRecipes)
   if err != nil {
   
      log.Fatal(err)
   }
   log.Println("Inserted recipes: ", len(insertManyResult.InsertedIDs))
}

MongoDB在插入数据的时候,只要没创建,就会默认创建指定数据模型的库(在MongoDB中库叫做collection 集合,插入的记录叫做document 文档)

collection.InsertMany接收interface{}切片类型的数据,所以上面把recipes数组的数据循环拷贝到listOfRecipes的interface切片中

recipes.json文件有如下内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值