Thiago Zilli Sarmento
Innovation enthusiast, Blockchain master and Techleader
Meetup GolangBR - Dicas do Mgo Driver
Descomplicando sua vida no MongoDB
Meetup GolangBR - Dicas do Mgo Driver
Considerações
1) MySQL != NoSQL
2) NoSQL temos "Schema Free"
3) NoSQL, Não é a bala de prata
4) Documentação
Meetup GolangBR - Dicas do Mgo Driver
Instalação e ambiente
$ gvm use go1.9 --default
$ go get -v -u gopkg.in/mgo.v2
Go version manager - https://github.com/moovweb/gvm
Mgo Driver - https://github.com/go-mgo/mgo
Meetup GolangBR - Dicas do Mgo Driver
Meetup GolangBR - Dicas do Mgo Driver
package dbs
import (
"log"
"time"
"os"
mgo "gopkg.in/mgo.v2"
)
//MgoSession and session
type MgoSession struct {
Session *mgo.Session
}
func newMgoSession(s *mgo.Session) *MgoSession {
return &MgoSession{s}
}
Importação dos pacotes, struct e New Session
Meetup GolangBR - Dicas do Mgo Driver
package dbs
import (
mgo "gopkg.in/mgo.v2"
)
//StartMongoDB initialize session on mongodb
func StartMongoDB(msg string) *MgoSession {
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{os.Getenv("MONGODB_URL")},
Timeout: 60 * time.Second,
Database: os.Getenv("MONGODB_DB"),
Username: os.Getenv("MONGODB_USER"),
Password: os.Getenv("MONGODB_PASS"),
}
mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("[MongoDB] CreateSession: %s\n", err)
}
mongoSession.SetMode(mgo.Monotonic, true)
mongoSession.SetSocketTimeout(1 * time.Hour)
ensureIndexMetupGolangBR(mongoSession)
log.Printf("[MongoDB] connected! %s", msg)
return newMgoSession(mongoSession)
}
Start e configuração de conecção
Meetup GolangBR - Dicas do Mgo Driver
func ensureIndexMetupGolangBR(s *mgo.Session) {
session := s.Copy()
defer session.Close()
c := session.DB("meetup").C("golangbr")
index := mgo.Index{
Key: []string{"field1",
"field2",
"field3",
"field4",
"field5"},
Unique: false,
DropDups: false,
Background: true,
Sparse: true,
}
if err := c.EnsureIndex(index); err != nil {
log.Printf("Error on create index: %s", err)
}
}
Índices e configuração
Meetup GolangBR - Dicas do Mgo Driver
package dbs
import (
"gopkg.in/mgo.v2"
)
//Dispatch dbs session
type Dispatch struct {
MongoDB *mgo.Session
RedisCache *RedisSession
}
//StartDispatch load up connections
func StartDispatch() *Dispatch {
//add session of mongodb
mongosession := StartMongoDB("Dispatch Service").Session
//add session of redis
redisCache := StartRedis("Dispatch Service")
return &Dispatch{MongoDB: mongosession, RedisCache: redisCache}
}
Sessões (dispatch)
Meetup GolangBR - Dicas do Mgo Driver
//GetAllProjectsByUser list all projects by user id
func GetAllProjectsByUser(s *db.Dispatch) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session := s.MongoDB.Copy()
defer session.Close()
//get user id from context
claims, ok := r.Context().Value(models.JwtKey).(models.Claims)
if !ok {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"message":"Missing token or token invalid"}`)
return
}
projects := []models.Project{}
oid := bson.ObjectIdHex(claims.UserID)
if err := session.DB("meetup").C("golangbr").
Find(bson.M{"users": oid}).
All(&projects); err != nil {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, `{"message":"Registry Not Found"}`)
return
}
uj, _ := json.Marshal(projects)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s", uj)
}
}
Controllers
Meetup GolangBR - Dicas do Mgo Driver
Highlights
Cluster discovery and communication
Failover management
Synchronous and concurrent
Result pre-fetching
Flexible serialization
Trivial consistency-level management
Authentication support with pooling integration
GridFS support
Meetup GolangBR - Dicas do Mgo Driver
Obrigado!
e-mail: thiago.zilli@gmail.com
twitter: @thiagozs
linkedin: https://www.linkedin.com/in/thiagozs/
By Thiago Zilli Sarmento
Dicas do mgo driver e alguns exemplos de codigo