Ai
1 Star 0 Fork 0

kzangv/gsf-fof-mongo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
client.go 4.32 KB
一键复制 编辑 原始数据 按行查看 历史
kzangv 提交于 2024-09-10 14:57 +08:00 . fixed
package mongo
import (
"context"
"fmt"
"gitee.com/kzangv/gsf-fof/logger"
"github.com/urfave/cli/v2"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
"net/url"
"strings"
"time"
)
type ClientConfig struct {
Host string `json:"host" yaml:"host"`
User string `json:"user" yaml:"user"`
Pwd string `json:"password" yaml:"password"`
DB string `json:"db" yaml:"db"`
DSN string `json:"dsn" yaml:"dsn"`
Options string `json:"options" yaml:"options"`
MinPoolSize int `json:"min_pool_size" yaml:"min_pool_size"`
MaxPoolSize int `json:"max_pool_size" yaml:"max_pool_size"`
}
type Client struct {
Client *mongo.Database
Cfg ClientConfig
ref *Component
Log logger.Interface
CreateClient func(c *ClientConfig, cc *Config) (es *mongo.Database, err error)
}
func (c *Client) Ref() *Component {
return c.ref
}
func (c *Client) CliFlags(name string) []cli.Flag {
return []cli.Flag{
&cli.IntFlag{
Name: fmt.Sprintf("mongo-%s-pool-min", name),
Usage: fmt.Sprintf("mongo(%s) min pool size", name),
Action: func(_ *cli.Context, v int) error { c.Cfg.MinPoolSize = v; return nil },
},
&cli.IntFlag{
Name: fmt.Sprintf("mongo-%s-pool-max", name),
Usage: fmt.Sprintf("mongo(%s) max pool size", name),
Action: func(_ *cli.Context, v int) error { c.Cfg.MaxPoolSize = v; return nil },
},
&cli.StringFlag{
Name: fmt.Sprintf("mongo-%s-dsn", name),
Usage: fmt.Sprintf("mongo(%s) DSN (format: `mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]`)", name),
Action: func(_ *cli.Context, val string) error {
_, err := connstring.ParseAndValidate(val)
if err == nil {
c.Cfg.DSN = val
}
if err != nil {
return fmt.Errorf("Mongo DSN is invalid(%s)[url parse faild err_msg:%s]", name, err.Error())
}
return nil
},
},
}
}
func (c *Client) Init() (err error) {
if c.Cfg.DSN != "" {
if pv, err := connstring.ParseAndValidate(c.Cfg.DSN); err == nil {
c.Cfg.Host = strings.Join(pv.Hosts, ",")
c.Cfg.User = pv.Username
c.Cfg.Pwd = pv.Password
c.Cfg.DB = pv.Database
c.Cfg.Options = url.Values(pv.Options).Encode()
} else {
return err
}
}
return nil
}
func (c *Client) Load(name string, cfg *Config) (err error) {
if c.CreateClient == nil {
c.CreateClient = DefaultNewClient1
}
c.Client, err = c.CreateClient(&c.Cfg, cfg)
if err != nil {
err = fmt.Errorf("Load Mongo (%s) Failed (Error: %s) ", name, err.Error())
c.Client = nil
}
return err
}
func DefaultNewClient1(c *ClientConfig, cc *Config) (es *mongo.Database, err error) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
connect, err := mongo.Connect(ctx, options.Client().
ApplyURI(fmt.Sprintf("mongodb://%s/%s?%s", c.Host, c.DB, c.Options)).
SetAuth(options.Credential{
Username: c.User,
Password: c.Pwd,
}).
SetMaxConnIdleTime(time.Second*time.Duration(cc.MaxIdleTime)).
SetTimeout(time.Second*time.Duration(cc.ReqMaxTime)).
SetServerSelectionTimeout(time.Second*time.Duration(cc.SelectionTime)).
SetMinPoolSize(uint64(c.MinPoolSize)).
SetMaxPoolSize(uint64(c.MaxPoolSize)))
if err != nil {
return nil, err
}
if err = connect.Ping(ctx, readpref.Primary()); err != nil {
return nil, err
}
return connect.Database(c.DB), nil
}
func DefaultNewClient2(c *ClientConfig, cc *Config) (es *mongo.Database, err error) {
if c.DSN == "" {
c.DSN = fmt.Sprintf("mongodb://%s:%s@%s/%s", c.User, c.Pwd, c.Host, c.DB)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
connect, err := mongo.Connect(ctx, options.Client().
ApplyURI(c.DSN).
SetMaxConnIdleTime(time.Second*time.Duration(cc.MaxIdleTime)).
SetTimeout(time.Second*time.Duration(cc.ReqMaxTime)).
SetServerSelectionTimeout(time.Second*time.Duration(cc.SelectionTime)).
SetMinPoolSize(uint64(c.MinPoolSize)).
SetMaxPoolSize(uint64(c.MaxPoolSize)))
if err == nil {
err = connect.Ping(ctx, readpref.Primary())
}
if err != nil {
err = fmt.Errorf("Load Mongo (%s) Failed (Error: %s) ", c.DB, err.Error())
} else {
return connect.Database(c.DB), nil
}
return nil, err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kzangv/gsf-fof-mongo.git
git@gitee.com:kzangv/gsf-fof-mongo.git
kzangv
gsf-fof-mongo
gsf-fof-mongo
v0.1.3

搜索帮助