mongodb_storage

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Mongodb Storage

一、这是什么

以MongoDB为存储引擎的Storage实现,当前仓库为比较底层的存储层实现,你可以与storage-lock结合使用。

二、安装

go get -u github.com/storage-lock/go-mongodb-storage

三、API示例

3.1 从URI创建MongodbStorage

package main

import (
	"context"
	"fmt"
	mongodb_storage "github.com/storage-lock/go-mongodb-storage"
)

func main() {

	// 使用一个uri形式的数据库连接字符串创建ConnectionManager
	uri := "mongodb://root:UeGqAm8CxYGldMDLoNNt@192.168.128.206:27017/?connectTimeoutMS=300000"
	connectionManager := mongodb_storage.NewMongoConnectionManager(uri)

	// 然后从这个ConnectionManager创建MongodbStorage
	options := mongodb_storage.NewMongoStorageOptions().SetConnectionManager(connectionManager)
	storage, err := mongodb_storage.NewMongoStorage(context.Background(), options)
	if err != nil {
		panic(err)
	}
	fmt.Println(storage.GetName())

}

3.2 从mongo.Client创建MongodbStorage

package main

import (
	"context"
	"fmt"
	mongodb_storage "github.com/storage-lock/go-mongodb-storage"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {

	// 假设已经在其它地方初始化数据库连接得到了一个*mongo.Client
	uri := "mongodb://root:UeGqAm8CxYGldMDLoNNt@192.168.128.206:27017/?connectTimeoutMS=300000"
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	// 则可以从这个*mongo.Client中创建一个Mongodb Storage
	connectionManager := mongodb_storage.NewMongoConnectionManagerFromClient(client)
	options := mongodb_storage.NewMongoStorageOptions().SetConnectionManager(connectionManager)
	storage, err := mongodb_storage.NewMongoStorage(context.Background(), options)
	if err != nil {
		panic(err)
	}
	fmt.Println(storage.GetName())

}

Documentation

Index

Constants

View Source
const MongoConnectionManagerName = "mongodb-connection-manager"
View Source
const MongoStorageName = "mongodb-storage"

Variables

View Source
var (

	// ErrDatabaseNameEmpty 参数中数据库名字为空
	ErrDatabaseNameEmpty = fmt.Errorf("DatabaseName can not empty")

	// ErrCollectionNameEmpty 参数中集合名字为空
	ErrCollectionNameEmpty = fmt.Errorf("CollectionName can not empty")

	// ErrConnectionManagerNil 连接管理器没有指定
	ErrConnectionManagerNil = fmt.Errorf("ConnectionManager can not nil")

	// ErrMongoNotInit 存储尚未初始化(GetTime 需要客户端连接)
	ErrMongoNotInit = fmt.Errorf("mongodb storage is not initialized")

	// ErrMongoServerTimeUnavailable MongoDB 未在 hello 响应中返回 localTime
	ErrMongoServerTimeUnavailable = fmt.Errorf("mongodb server time is unavailable")
)

Functions

This section is empty.

Types

type ListMongoLockIterator

type ListMongoLockIterator struct {
	// contains filtered or unexported fields
}

ListMongoLockIterator 用于迭代列出mongo中的所有的锁

func NewListMongoLockIterator

func NewListMongoLockIterator(cursor *mongo.Cursor) *ListMongoLockIterator

func (*ListMongoLockIterator) Next

func (x *ListMongoLockIterator) Next() bool

func (*ListMongoLockIterator) Value

Value 返回当前游标指向的锁信息。

MongoDB 中锁记录以 MongoLock(bson 字段:_id/owner_id/version/lock_json_string)存储, 真正的 LockInformation(包含 LockId/LockCount/ReadLock 等字段)被序列化保存在 lock_json_string 字段里。之前直接把 bson 文档 Decode 到 storage.LockInformation (它只有 json tag,没有 bson tag)会导致除 OwnerId/Version 外的字段全部零值, ReadLock/LockCount/LeaseExpireTime 等信息在 List 结果中全部丢失。 因此这里先 decode 到 MongoLock,再从 lock_json_string 解析出真正的 LockInformation。

type MongoConnectionManager

type MongoConnectionManager struct {

	// 连接到数据库的地址
	URI string
	// contains filtered or unexported fields
}

MongoConnectionManager 负责维护与Mongo数据库的连接

func NewMongoConnectionManagerFromClient

func NewMongoConnectionManagerFromClient(client *mongo.Client) *MongoConnectionManager

NewMongoConnectionManagerFromClient 复用已经存在的mongo client,从其创建连接管理器

func NewMongoConnectionManagerFromURI

func NewMongoConnectionManagerFromURI(uri string) *MongoConnectionManager

NewMongoConnectionManagerFromURI 从Mongo uri创建连接管理器

func (*MongoConnectionManager) Name

func (x *MongoConnectionManager) Name() string

func (*MongoConnectionManager) Return

func (x *MongoConnectionManager) Return(ctx context.Context, connection *mongo.Client) error

func (*MongoConnectionManager) Shutdown

func (x *MongoConnectionManager) Shutdown(ctx context.Context) error

func (*MongoConnectionManager) Take

Take 获取 Mongo 客户端。

漏洞4 修复:原 sync.Once 在 mongo.Connect 失败时永久缓存 err,无法重试。 mongo.Connect 可能因网络/DNS 问题失败,永久缓存对临时性故障不友好(liveness)。 改为 mutex + initialized:成功后缓存 client 不重复 Connect;失败不缓存 err 可重试。

type MongoLock

type MongoLock struct {

	// 锁的ID,这个字段是一个唯一字段,这个字段会作为Mongo中的Collection的主键字段,保证同一个锁同时只会存在一个
	ID string `bson:"_id"`

	// 锁的当前持有者的ID
	OwnerId string `bson:"owner_id"`

	// 锁的版本,每次修改都会增加1
	Version storage.Version `bson:"version"`

	// 锁的json信息,存储着更上层的通用的锁的信息,这里只需要认为它是一个字符串就可以了
	LockJsonString string `bson:"lock_json_string"`
}

MongoLock 锁在Mongo中存储的结构

type MongoStorage

type MongoStorage struct {
	// contains filtered or unexported fields
}

MongoStorage MongoDB的存储引擎实现

func NewMongoStorage

func NewMongoStorage(ctx context.Context, options *MongoStorageOptions) (*MongoStorage, error)

NewMongoStorage 创建一个基于MongoDB的存储引擎

func (*MongoStorage) Capabilities

func (x *MongoStorage) Capabilities() []storage.StorageCapability

Capabilities 声明 MongoDB 存储支持的能力 MongoDB 通过唯一索引 + 条件更新支持 CAS, 通过 NTP 时间源提供可靠时间,且支持 Change Streams 作为 Watch 能力

func (*MongoStorage) Close

func (x *MongoStorage) Close(ctx context.Context) error

func (*MongoStorage) CreateWithVersion

func (x *MongoStorage) CreateWithVersion(ctx context.Context, lockId string, version storage.Version, lockInformation *storage.LockInformation) error

func (*MongoStorage) DeleteWithVersion

func (x *MongoStorage) DeleteWithVersion(ctx context.Context, lockId string, exceptedVersion storage.Version, lockInformation *storage.LockInformation) error

func (*MongoStorage) Get

func (x *MongoStorage) Get(ctx context.Context, lockId string) (string, error)

func (*MongoStorage) GetName

func (x *MongoStorage) GetName() string

func (*MongoStorage) GetTime

func (x *MongoStorage) GetTime(ctx context.Context) (time.Time, error)

func (*MongoStorage) Init

func (x *MongoStorage) Init(ctx context.Context) error

func (*MongoStorage) List

func (*MongoStorage) UpdateWithVersion

func (x *MongoStorage) UpdateWithVersion(ctx context.Context, lockId string, exceptedVersion, newVersion storage.Version, lockInformation *storage.LockInformation) error

func (*MongoStorage) Watch

func (x *MongoStorage) Watch(ctx context.Context, lockId string) (<-chan *storage.LockInformation, error)

type MongoStorageOptions

type MongoStorageOptions struct {

	// 获取连接
	ConnectionManager storage.ConnectionManager[*mongo.Client]

	// 要存储到的数据库的名称
	DatabaseName string

	// 集合名称
	CollectionName string

	// TimeProvider 可选,自定义时间源。MongoDB 本身没有便捷的方式拿到服务器时间,
	// 默认使用公共 NTP(见 GetTime),但公共 NTP 依赖外网可达性,延迟也不稳定;
	// 内网部署或测试场景可以通过这里注入自定义实现(比如指向内网 NTP,或直接用
	// 本地时钟)来避免这个依赖。为空则回退到默认的 NTP 实现。
	TimeProvider storage.TimeProvider
}

MongoStorageOptions Mongo的存储选项

func NewMongoStorageOptions

func NewMongoStorageOptions() *MongoStorageOptions

func NewMongoStorageOptionsWithURI

func NewMongoStorageOptionsWithURI(uri string) *MongoStorageOptions

func (*MongoStorageOptions) Check

func (x *MongoStorageOptions) Check() error

func (*MongoStorageOptions) SetCollectionName

func (x *MongoStorageOptions) SetCollectionName(collectionName string) *MongoStorageOptions

func (*MongoStorageOptions) SetConnectionManager

func (x *MongoStorageOptions) SetConnectionManager(connectionProvider storage.ConnectionManager[*mongo.Client]) *MongoStorageOptions

func (*MongoStorageOptions) SetDatabaseName

func (x *MongoStorageOptions) SetDatabaseName(databaseName string) *MongoStorageOptions

func (*MongoStorageOptions) SetTimeProvider

func (x *MongoStorageOptions) SetTimeProvider(timeProvider storage.TimeProvider) *MongoStorageOptions

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址