go调用Mongdb注册回调函数(mongo-driver/mongo)

  • Post author:
  • Post category:其他



ServerMonitor

表示为不同的服务器事件触发的监视器。 客户端

将监视它所连接的

MongoDB

部署的变化,这个监视报告

在客户端表示部署的变化。

总体部署,和心跳被发送到单个服务器,以检查它们的当前状态。


mongodb

提供检测服务器得非阻塞式的接口

type ServerMonitor struct {
	ServerDescriptionChanged func(*ServerDescriptionChangedEvent)
	ServerOpening            func(*ServerOpeningEvent)
	ServerClosed             func(*ServerClosedEvent)
	TopologyDescriptionChanged func(*TopologyDescriptionChangedEvent)
	TopologyOpening            func(*TopologyOpeningEvent)
	TopologyClosed             func(*TopologyClosedEvent)
	ServerHeartbeatStarted     func(*ServerHeartbeatStartedEvent)
	ServerHeartbeatSucceeded   func(*ServerHeartbeatSucceededEvent)
	ServerHeartbeatFailed      func(*ServerHeartbeatFailedEvent)
}


SetServerMonitor

指定用于监视

SDAM

事件的

SDAM

监视器。

使用实例,应该重写需要监听的回调接口

var status bool

func GetServerStatus() *bool {
	return &status
}
func serverClosed(e *event.ServerClosedEvent) {
	serverStatus := GetServerStatus()
	*serverStatus = false // 服务器关闭状态
}
func serverOpened(e *event.ServerOpeningEvent) {
	serverStatus := GetServerStatus()
	*serverStatus = true // 服务器关闭状态
	fmt.Println("打开了")
}
func serverHearbeatFailed(e *event.ServerHeartbeatStartedEvent) {
	serverStatus := GetServerStatus()
	*serverStatus = true // 服务开启,心跳检测成功
}
func serverHearFailed(e *event.ServerHeartbeatFailedEvent)  {
	serverStatus := GetServerStatus()
	*serverStatus = false
	fmt.Println("服务挂了")
}

当连接进行初始化的时候,就把这些回调函数注册到连接中去

func DBConnectInit() {
	ctx2, _ := context.WithTimeout(context.Background(), 10*time.Second)
	monitor := &event.ServerMonitor{
		ServerDescriptionChanged:   nil,
		ServerOpening:              serverOpened,
		ServerClosed:               serverClosed,
		TopologyDescriptionChanged: nil,
		TopologyOpening:            nil,
		TopologyClosed:             nil,
		ServerHeartbeatStarted:     serverHearbeatFailed,
		ServerHeartbeatSucceeded:   nil,
		ServerHeartbeatFailed:      serverHearFailed,
	}
    // 一个事件的注册器 把写过的函数注册进去
	var err error
	client,err = mongo.Connect(ctx2, options.Client().ApplyURI("mongodb://localhost:27017").SetServerMonitor(monitor).SetHeartbeatInterval(1*time.Second))
    // SetHeartbeatInterval 用于指定心跳间隔
	if err != nil {
		log.Panic("client error ",err)
	}
    fmt.Println("启动中")
	// client.Disconnect(ctx)
	globalH = client.Database("test").Collection("col") 
}
/*
type Client struct {
	id              uuid.UUID
	
	monitor         *event.CommandMonitor
	serverAPI       *driver.ServerAPIOptions
	serverMonitor   *event.ServerMonitor // 关于事件的
	sessionPool     *session.Pool

}
*/

每当需要获取连接的时候就应该判断服务器的状态

func GetConnect() *mongo.Client { // 获取一个连接过来
	serverStatus := GetServerStatus()
	if *serverStatus == false {
		return nil
	}
	return client
}

这样,就不必要时时去

ping

服务器,只需要对他进行注册回调和设置心跳间隔既可以轻松实现非阻塞的高效连接。



版权声明:本文为m0_47178337原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。