Listening to Connection Events
Elemental provides a way to listen to connection pool events such as ConnectionCreated
, ConnectionReady
, and ConnectionClosed
in a much more user-friendly way.
- Listens to the
ConnectionCreated
event of the default connection
elemental.OnConnectionEvent("ConnectionCreated", func(alias string) {
fmt.Println("Connection created for", alias)
})
- Listens to the
ConnectionCreated
event of a specific connection
elemental.OnConnectionEvent("ConnectionCreated", func(alias string) {
fmt.Println("Connection created for", alias)
}, "my-connection")
Unsubscribe from Connection Events
- Unsubscribes from the
ConnectionCreated
event of the default connection
elemental.RemoveConnectionEvent("ConnectionCreated")
- Unsubscribes from the
ConnectionCreated
event of a specific connection
elemental.RemoveConnectionEvent("ConnectionCreated", "my-connection")
For a full list of supported events, refer this page.
Override the default Elemental pool monitor
Elemental adds a default pool monitor to the connection pool to listen to connection events. You can override this monitor with your own custom monitor by providing one when creating a connection.
poolMonitor := &event.PoolMonitor{
Event: func(evt *event.PoolEvent) {
fmt.Println("Pool event:", evt)
},
}
client := elemental.Connect(elemental.ConnectionOptions{
URI: "mongodb://localhost:27017",
PoolMonitor: poolMonitor,
})