系列文章目录
第一章 gin初步认识 第二章 设置API 第三章 使用MongoDB数据持久化
目录
系列文章目录
使用MongoDB数据持久化
前言
go使用mongodb
CRUD操作实例
查找
插入一条记录
更新一条记录
设计项目的分层结构
handler.go设计
使用redis缓存API
查询的情况
docker运行redis
配置redis
使用redis对数据缓存的代码
直接查看redis缓存是否存在
网站性能跑分
注:
系列文章是对应上述英文原版书的学习笔记
相关自己的练习代码包含注释,放在在本人的gitee,欢迎star
所有内容允许转载,如果侵犯书籍的著作权益,请联系删除
笔记持续更新中
使用MongoDB数据持久化
前言
本章将会用docker部署MongoDB和Redis,实现CRUD,介绍标准go项目目录结构,优化API响应提高网站性能
go使用mongodb
在项目中获取依赖
go get go.mongodb.org/mongo-driver/mongo
这将会下载驱动到系统GOPath,并把其作为依赖写入go.mod文件中
连接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() {
}
使用上一章的数据初始化数据库
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
好文链接
发表评论