close finalizer
This commit is contained in:
parent
75e76fb056
commit
709ca7f23b
33
mgo.go
33
mgo.go
@ -2,37 +2,66 @@ package mgocrud
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
mgo "gopkg.in/mgo.v2"
|
mgo "gopkg.in/mgo.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MgoConnection struct {
|
type MgoConnection struct {
|
||||||
connection *mgo.Session
|
connection *mgo.Session
|
||||||
|
closed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMgoConnection(dial string) (Connection, error) {
|
func NewMgoConnection(dial string) (Connection, error) {
|
||||||
|
fmt.Println("CONNECTION CREATE")
|
||||||
connection, err := mgo.Dial(dial)
|
connection, err := mgo.Dial(dial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
connection.SetMode(mgo.Monotonic, true)
|
connection.SetMode(mgo.Monotonic, true)
|
||||||
return &MgoConnection{connection: connection}, nil
|
c := &MgoConnection{connection: connection}
|
||||||
|
runtime.SetFinalizer(c, func(c *MgoConnection) {
|
||||||
|
fmt.Println("CONNECTION CLOSE FINALIZER")
|
||||||
|
if !c.closed {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MgoConnection) Close() {
|
func (c *MgoConnection) Close() {
|
||||||
|
fmt.Println("CONNECTION CLOSE MANUALLY")
|
||||||
|
if !c.closed {
|
||||||
c.connection.Close()
|
c.connection.Close()
|
||||||
|
c.closed = true
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(c, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
type MgoSession struct {
|
type MgoSession struct {
|
||||||
session *mgo.Session
|
session *mgo.Session
|
||||||
|
closed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MgoSession) Close() {
|
func (s *MgoSession) Close() {
|
||||||
|
fmt.Println("SESSION CLOSE MANUALLY")
|
||||||
|
if !s.closed {
|
||||||
s.session.Close()
|
s.session.Close()
|
||||||
|
s.closed = true
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(s, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MgoConnection) NewSession() Session {
|
func (c *MgoConnection) NewSession() Session {
|
||||||
return &MgoSession{session: c.connection.Copy()}
|
fmt.Println("SESSION CREATE")
|
||||||
|
s := &MgoSession{session: c.connection.Copy()}
|
||||||
|
runtime.SetFinalizer(s, func(s *MgoSession) {
|
||||||
|
fmt.Println("SESSION CLOSE FINALIZER")
|
||||||
|
if !s.closed {
|
||||||
|
s.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type MgoDatabase struct {
|
type MgoDatabase struct {
|
||||||
|
Loading…
Reference in New Issue
Block a user