emongo

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: MIT Imports: 29 Imported by: 0

README

emongo 组件使用指南

goproxy.cn Release Example Doc

1 简介

mongo-driver 进行了轻量封装,并提供了以下功能:

  • 规范了标准配置格式,提供了统一的 Load().Build() 方法。
  • 支持自定义拦截器
  • 提供了默认的 Debug 拦截器,开启 Debug 后可输出 Request、Response 至终端。
  • 提供了默认的 Metric 拦截器,开启后可采集 Prometheus 指标数据

2 使用方式

go get github.com/ego-component/emongo

3 mongo配置

type Config struct {
    DSN                        string        `json:"dsn" toml:"dsn"`     // DSN DSN地址
    Debug                      bool          `json:"debug" toml:"debug"` // Debug 是否开启debug模式
    DialTimeout                time.Duration // 连接超时
    SocketTimeout              time.Duration `json:"socketTimeout" toml:"socketTimeout"` // SocketTimeout 创建连接的超时时间
    MaxConnIdleTime            time.Duration `json:"maxConnIdleTime"`
    MinPoolSize                int           // MinPoolSize 连接池大小(最小连接数)
    MaxPoolSize                int           `json:"maxPoolSize" toml:"maxPoolSize"`                               // MaxPoolSize 连接池大小(最大连接数)
    EnableMetricInterceptor    bool          `json:"enableMetricInterceptor" toml:"enableMetricInterceptor"`       // EnableMetricInterceptor 是否启用prometheus metric拦截器
    EnableAccessInterceptorReq bool          `json:"enableAccessInterceptorReq" toml:"enableAccessInterceptorReq"` // EnableAccessInterceptorReq 是否启用access req拦截器,此配置只有在EnableAccessInterceptor=true时才会生效
    EnableAccessInterceptorRes bool          `json:"enableAccessInterceptorRes" toml:"enableAccessInterceptorRes"` // EnableAccessInterceptorRes 是否启用access res拦截器,此配置只有在EnableAccessInterceptor=true时才会生效
    EnableAccessInterceptor    bool          `json:"enableAccessInterceptor" toml:"enableAccessInterceptor"`       // EnableAccessInterceptor 是否启用access拦截器
    EnableTraceInterceptor     bool          `json:"enableTraceInterceptor" toml:"enableTraceInterceptor"`         // EnableTraceInterceptor 是否启用trace拦截器
    SlowLogThreshold           time.Duration // SlowLogThreshold 慢日志门限值,超过该门限值的请求,将被记录到慢日志中
    // TLS 支持
    Authentication Authentication
}

4 优雅的Debug

通过开启debug配置和命令行的export EGO_DEBUG=true,我们就可以在测试环境里看到请求里的配置名、地址、耗时、请求数据、响应数据 img.png

5 用户配置

[mongo]
  debug=true
  dsn="mongodb://user:password@localhost:27017,localhost:27018"
  [mongo.authentication]
    [mongo.authentication.tls]
      enabled=false
      CAFile=""
      CertFile="./cert/tls.pem"
      KeyFile="./cert/tls.key"
      insecureSkipVerify=true

6 用户代码

var stopCh = make(chan bool)
	// 假设你配置的toml如下所示
	conf := `
[mongo]
	debug=true
	dsn="mongodb://user:password@localhost:27017,localhost:27018"
`
	// 加载配置文件
err := econf.LoadFromReader(strings.NewReader(conf), toml.Unmarshal)
if err != nil {
    panic("LoadFromReader fail," + err.Error())
}

// 初始化emongo组件
cmp := emongo.Load("mongo").Build()
coll := cmp.Client.Database("test").Collection("cells")
findOne(coll)

stopCh <- true

Documentation

Overview

Copyright 2018, OpenCensus Authors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const PackageName = "component.emongo"

Variables

This section is empty.

Functions

func DefaultConfig

func DefaultConfig() *config

DefaultConfig 返回默认配置

func InterceptorChain

func InterceptorChain(interceptors ...Interceptor) func(oldProcess processFn) processFn

func WithSession

func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error

Types

type Authentication added in v1.0.1

type Authentication struct {
	// TLS authentication
	TLS *TLSConfig
}

func (*Authentication) ConfigureAuthentication added in v1.0.1

func (config *Authentication) ConfigureAuthentication(opts *options.ClientOptions) (err error)

type Client

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

func Connect

func Connect(ctx context.Context, opts ...*options.ClientOptions) (wc *Client, err error)

func NewClient

func NewClient(opts ...*options.ClientOptions) (*Client, error)

func (*Client) Client

func (wc *Client) Client() *mongo.Client

func (*Client) Connect

func (wc *Client) Connect(ctx context.Context) error

func (*Client) Database

func (wc *Client) Database(name string, opts ...*options.DatabaseOptions) *Database

func (*Client) Disconnect

func (wc *Client) Disconnect(ctx context.Context) error

func (*Client) ListDatabaseNames

func (wc *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (
	dbs []string, err error)

func (*Client) ListDatabases

func (wc *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (
	dbr mongo.ListDatabasesResult, err error)

func (*Client) NewClientEncryption

func (wc *Client) NewClientEncryption(opts ...*options.ClientEncryptionOptions) (*ClientEncryption, error)

func (*Client) Ping

func (wc *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error

func (*Client) StartSession

func (wc *Client) StartSession(opts ...*options.SessionOptions) (ss Session, err error)

func (*Client) UseSession

func (wc *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error

func (*Client) UseSessionWithOptions

func (wc *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, fn func(SessionContext) error) error

type ClientEncryption

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

func (*ClientEncryption) Close

func (wce *ClientEncryption) Close(ctx context.Context) error

func (*ClientEncryption) CreateDataKey

func (wce *ClientEncryption) CreateDataKey(ctx context.Context, kmsProvider string, opts ...*options.DataKeyOptions) (
	id primitive.Binary, err error)

func (*ClientEncryption) Decrypt

func (wce *ClientEncryption) Decrypt(ctx context.Context, val primitive.Binary) (value bson.RawValue, err error)

func (*ClientEncryption) Encrypt

func (wce *ClientEncryption) Encrypt(ctx context.Context, val bson.RawValue, opts ...*options.EncryptOptions) (
	value primitive.Binary, err error)

type Collection

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

func (*Collection) Aggregate

func (wc *Collection) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (res *mongo.Cursor, err error)

func (*Collection) BulkWrite

func (wc *Collection) BulkWrite(ctx context.Context, models []mongo.WriteModel, opts ...*options.BulkWriteOptions) (
	res *mongo.BulkWriteResult, err error)

func (*Collection) Clone

func (wc *Collection) Clone(opts ...*options.CollectionOptions) (res *mongo.Collection, err error)

func (*Collection) Collection

func (wc *Collection) Collection() *mongo.Collection

func (*Collection) CountDocuments

func (wc *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (res int64, err error)

func (*Collection) Database

func (wc *Collection) Database() *mongo.Database

func (*Collection) DeleteMany

func (wc *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (
	res *mongo.DeleteResult, err error)

func (*Collection) DeleteOne

func (wc *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (res *mongo.DeleteResult, err error)

func (*Collection) Distinct

func (wc *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) (res []interface{}, err error)

func (*Collection) Drop

func (wc *Collection) Drop(ctx context.Context) error

func (*Collection) EstimatedDocumentCount

func (wc *Collection) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (res int64, err error)

func (*Collection) Find

func (wc *Collection) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (res *mongo.Cursor, err error)

func (*Collection) FindOne

func (wc *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) (res *mongo.SingleResult)

func (*Collection) FindOneAndDelete

func (wc *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) (res *mongo.SingleResult)

func (*Collection) FindOneAndReplace

func (wc *Collection) FindOneAndReplace(ctx context.Context, filter, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) (res *mongo.SingleResult)

func (*Collection) FindOneAndUpdate

func (wc *Collection) FindOneAndUpdate(ctx context.Context, filter, update interface{}, opts ...*options.FindOneAndUpdateOptions) (res *mongo.SingleResult)

func (*Collection) Indexes

func (wc *Collection) Indexes() mongo.IndexView

func (*Collection) InsertMany

func (wc *Collection) InsertMany(ctx context.Context, documents []interface{}, opts ...*options.InsertManyOptions) (res *mongo.InsertManyResult, err error)

func (*Collection) InsertOne

func (wc *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (res *mongo.InsertOneResult, err error)

func (*Collection) Name

func (wc *Collection) Name() string

func (*Collection) ReplaceOne

func (wc *Collection) ReplaceOne(ctx context.Context, filter, replacement interface{}, opts ...*options.ReplaceOptions) (res *mongo.UpdateResult, err error)

func (*Collection) UpdateByID added in v1.0.1

func (wc *Collection) UpdateByID(ctx context.Context, id interface{}, update interface{}, opts ...*options.UpdateOptions) (res *mongo.UpdateResult, err error)

func (*Collection) UpdateMany

func (wc *Collection) UpdateMany(ctx context.Context, filter, replacement interface{}, opts ...*options.UpdateOptions) (res *mongo.UpdateResult, err error)

func (*Collection) UpdateOne

func (wc *Collection) UpdateOne(ctx context.Context, filter, replacement interface{}, opts ...*options.UpdateOptions) (res *mongo.UpdateResult, err error)

func (*Collection) Watch

func (wc *Collection) Watch(ctx context.Context, pipeline interface{}, opts ...*options.ChangeStreamOptions) (res *mongo.ChangeStream, err error)

type Component

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

Component client (cmdable and config)

func (*Component) Client

func (c *Component) Client() *Client

Client returns emongo Client

func (*Component) DbName added in v1.0.2

func (c *Component) DbName() string

DbName returns emongo Client

type Container

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

func DefaultContainer

func DefaultContainer() *Container

DefaultContainer 返回默认Container

func Load

func Load(key string) *Container

Load 载入配置,初始化Container

func (*Container) Build

func (c *Container) Build(options ...Option) *Component

Build 构建Container

type Database

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

func (*Database) Client

func (wd *Database) Client() *Client

func (*Database) Collection

func (wd *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection

func (*Database) Database

func (wd *Database) Database() *mongo.Database

func (*Database) Drop

func (wd *Database) Drop(ctx context.Context) error

func (*Database) ListCollections

func (wd *Database) ListCollections(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (
	cur *mongo.Cursor, err error)

func (*Database) Name

func (wd *Database) Name() string

func (*Database) ReadConcern

func (wd *Database) ReadConcern() *readconcern.ReadConcern

func (*Database) ReadPreference

func (wd *Database) ReadPreference() *readpref.ReadPref

func (*Database) RunCommand

func (wd *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (res *mongo.SingleResult)

func (*Database) WriteConcern

func (wd *Database) WriteConcern() (res *writeconcern.WriteConcern)

type Interceptor

type Interceptor func(oldProcessFn processFn) (newProcessFn processFn)

type Option

type Option func(c *Container)

func WithDSN

func WithDSN(dsn string) Option

WithDSN 注入DSN配置

func WithDebug

func WithDebug(debug bool) Option

WithDebug 注入Debug配置

func WithInterceptor

func WithInterceptor(interceptors ...Interceptor) Option

WithInterceptor 注入拦截器

type Session

type Session = mongo.Session

type SessionContext

type SessionContext = mongo.SessionContext

type TLSConfig added in v1.0.1

type TLSConfig struct {
	// Enable TLS
	Enabled bool
	// Path to the CA cert. For a client this verifies the server certificate.
	CAFile string
	// Path to the TLS cert to use for TLS required connections. (optional)
	CertFile string
	// Path to the TLS key to use for TLS required connections. (optional)
	KeyFile string
	// InsecureSkipVerify will enable TLS but not verify the certificate
	InsecureSkipVerify bool
	// MinVersion sets the minimum TLS version that is acceptable.
	// If not set, TLS 1.2 will be used. (optional)
	MinVersion string
	// MaxVersion sets the maximum TLS version that is acceptable.
	// If not set, refer to crypto/tls for defaults. (optional)
	MaxVersion string
}

TLSConfig is the interface used to configure a tcp client or server from a `Config`

func (*TLSConfig) LoadTLSConfig added in v1.0.1

func (c *TLSConfig) LoadTLSConfig() (*tls.Config, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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