本文整理汇总了Golang中github.com/dancannon/gorethink.Connect函数的典型用法代码示例。如果您正苦于以下问题:Golang Connect函数的具体用法?Golang Connect怎么用?Golang Connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Init
// Init ...
func (rthink *RethinkDBImpl) Init(conntype string, dbhost string, username string, password string, port int, dbname string, log log.Logger, hosts ...string) error {
var retErr error
if conntype == "cluster" {
session, err := r.Connect(r.ConnectOpts{
Addresses: hosts,
Database: dbname,
AuthKey: password,
})
retErr = err
if err != nil {
log.Crit("Got error when connect database, the error is '%v'", err)
return retErr
}
rthink.Session = session
} else {
session, err := r.Connect(r.ConnectOpts{
Address: dbhost,
Database: dbname,
AuthKey: password,
})
retErr = err
if err != nil {
log.Crit("Got error when connect database, the error is '%v'", err)
return retErr
}
rthink.Session = session
}
fmt.Println("Rethink Connected")
return nil
}
示例2: init
func init() {
Log = logrus.New()
session, err := r.Connect(r.ConnectOpts{
Address: "172.17.8.150:32768",
Database: "gettingstarted",
})
if err != nil {
log.WithFields(log.Fields{
"Error": err,
}).Error("Error getting rethink")
}
// if err = r.DbCreate("gettingstarted").Run(session).Exec(); err != nil {
resp, err := r.DBCreate("gettingstarted").RunWrite(session)
if err != nil {
log.WithFields(log.Fields{
"Error": err,
}).Error("Error creating db")
}
fmt.Printf("RESP: %+v\n", resp.DBsCreated)
// if err = r.TableCreate("bookmarks").Run(session).Exec(); err != nil {
resp, err = r.DB("gettingstarted").TableCreate("bookmarks").RunWrite(session)
if err != nil {
log.WithFields(log.Fields{
"Error": err,
}).Error("Error creating table")
}
fmt.Printf("RESP %+v\n", resp.TablesCreated)
}
示例3: New
func New(conf Conf) (*Engine, error) {
if len(conf.DBAddress) == 0 {
return nil, ErrInvalidAddress
}
if len(conf.DBDatabase) == 0 {
return nil, ErrInvalidDB
}
logger := log.New(os.Stdout, "[entrapped models]", log.Ldate|log.Ltime|log.Lshortfile)
session, sessionErr := r.Connect(r.ConnectOpts{
Address: conf.DBAddress,
Database: conf.DBDatabase,
AuthKey: conf.DBAuthKey,
Timeout: conf.DBTimeout,
MaxIdle: conf.DBMaxIdle,
MaxOpen: conf.DBMaxOpen,
})
if sessionErr != nil {
logger.Println(sessionErr)
return nil, ErrRethinkConn
}
return &Engine{logger, r.DB(conf.DBDatabase), session}, nil
}
示例4: newLogger
func newLogger() (*Logger, error) {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
pubsub, err := client.Subscribe("messages")
session, err := rdb.Connect(rdb.ConnectOpts{
Address: "localhost:28015",
})
if err != nil {
panic(err)
}
logger := &Logger{
Redis: client,
Pubsub: pubsub,
DbSession: session,
messages: make(chan string),
}
go logger.handleMessages()
return logger, err
}
示例5: InitDBs
// InitDBs prepares a RethinkDB instance to be used by rethinkClient.
// rethinkClients will error if they are pointed at databases that haven't had
// InitDBs run on them
// InitDBs should only be run once per instance of RethinkDB, it will error if
// it's called a second time.
func InitDBs(address string, databaseName string) error {
session, err := gorethink.Connect(gorethink.ConnectOpts{Address: address})
if err != nil {
return err
}
if _, err := gorethink.DBCreate(databaseName).RunWrite(session); err != nil {
return err
}
for _, table := range tables {
tableCreateOpts, ok := tableToTableCreateOpts[table]
if ok {
if _, err := gorethink.DB(databaseName).TableCreate(table, tableCreateOpts...).RunWrite(session); err != nil {
return err
}
} else {
if _, err := gorethink.DB(databaseName).TableCreate(table).RunWrite(session); err != nil {
return err
}
}
}
for table, indexes := range tableToIndexes {
for _, index := range indexes {
if _, err := gorethink.DB(databaseName).Table(table).IndexCreate(index).RunWrite(session); err != nil {
return err
}
}
}
return nil
}
示例6: Connect
// Connect to the database.
func Connect() (err error) {
// Connext to the database server.
Session, err = r.Connect(r.ConnectOpts{
Address: settings.Settings.DBAddress,
Addresses: settings.Settings.DBAddresses,
Database: settings.Settings.DBName,
MaxIdle: settings.Settings.DBMaxIdle,
MaxOpen: settings.Settings.DBMaxOpen,
Timeout: settings.Settings.DBTimeout,
AuthKey: settings.Settings.DBAuthKey,
// When DiscoverHosts is true any nodes are added to the cluster after
// the initial connection then the new node will be added to the pool of
// available nodes used by GoRethink. Unfortunately the canonical address
// of each server in the cluster MUST be set as otherwise clients will
// try to connect to the database nodes locally. For more information
// about how to set a RethinkDB servers canonical address set
// this page http://www.rethinkdb.com/docs/config-file/.
DiscoverHosts: true,
})
if err != nil {
return fmt.Errorf("failed to connect to database: %v", err)
}
return nil
}
示例7: main
func main() {
dbAddress := util.GetKeyValue("RethinkDB", "address")
var err error
session, err = db.Connect(db.ConnectOpts{
Address: dbAddress,
Database: "travelPlanning",
})
if err != nil {
log.Fatalln(err.Error())
}
log.Println("Connected to db on: " + dbAddress)
tasks := mq.NewMQ()
tasks.NewQueue("TripWorkerQueue", "Trip")
msgs := tasks.GetMessages("TripWorkerQueue")
forever := make(chan bool)
go func() {
for d := range msgs {
var message mq.Message
json.Unmarshal(d.Body, &message)
processMessage(&message)
tasks.PublishMessage(message, d.ReplyTo, d.CorrelationId, "")
}
}()
log.Printf(" [*] Awaiting for requests")
<-forever
}
示例8: scrape
func (e *Exporter) scrape(scrapes chan<- scrapeResult) {
defer close(scrapes)
now := time.Now().UnixNano()
e.totalScrapes.Inc()
sess, err := r.Connect(r.ConnectOpts{
Addresses: e.addrs,
Database: "rethinkdb",
AuthKey: e.auth,
})
errCount := 0
if err == nil {
if err := extractAllMetrics(sess, scrapes); err != nil {
errCount++
}
sess.Close()
}
if err != nil {
log.Printf("scrape err: %s", err)
}
e.scrapeError.Set(float64(errCount))
e.duration.Set(float64(time.Now().UnixNano()-now) / 1000000000)
}
示例9: NewRethinkDBAdapter
func NewRethinkDBAdapter(c *CAS) (*RethinkDBAdapter, error) {
// Database setup
dbSession, err := r.Connect(r.ConnectOpts{
Address: c.Config["dbHost"],
Database: c.Config["dbName"],
})
if err != nil {
return nil, err
}
// Create the adapter
adapter := &RethinkDBAdapter{
session: dbSession,
dbName: c.Config["dbName"],
ticketsTableName: "tickets",
ticketsTableOptions: nil,
servicesTableName: "services",
servicesTableOptions: &r.TableCreateOpts{PrimaryKey: "name"},
usersTableName: "users",
usersTableOptions: &r.TableCreateOpts{PrimaryKey: "email"},
apiKeysTableName: "api_keys",
apiKeysTableOptions: &r.TableCreateOpts{PrimaryKey: "key"},
LogLevel: c.Config["logLevel"],
}
return adapter, nil
}
示例10: NewDBSession
//NewDBSession creates a new session to manage database data
func NewDBSession(database string) *r.Session {
conn, err := r.Connect(r.ConnectOpts{
Address: GetKeyValue("database", "address"),
Database: database,
MaxOpen: 40,
})
if err != nil {
log.Fatalln(err)
return nil
}
log.Infof("Connected to RethinkDB %s", GetKeyValue("database", "address"))
status, err := createDB(database, conn)
if err != nil {
log.Fatalln(err)
} else {
log.Info(status)
}
tables := []string{"Trip", "Place", "User"}
total, err := createTables(database, tables, conn)
if err != nil {
log.Fatalln(err)
} else {
log.Infof("%d new table(s) created", total)
}
return conn
}
示例11: init
func init() {
flag.Parse()
err := gcfg.ReadFileInto(&cfg, *configFile)
if err != nil {
log.Fatal(err)
}
session, err = r.Connect(r.ConnectOpts{
Address: cfg.Database.Host + ":" + cfg.Database.Port, //localhost:28015
Database: cfg.Database.DB, //DB: cats
})
if err != nil {
log.Fatal("Could not connect")
}
res, err := r.DBCreate(cfg.Database.DB).RunWrite(session)
if err != nil {
log.Println(err.Error())
}
fmt.Printf("%d DB created\n", res.DBsCreated)
r.DB(cfg.Database.DB).TableCreate("instacat").Run(session)
log.Println("Create table instacat.")
r.Table("instacat").IndexCreate("time").Run(session)
log.Println("Create index time.")
r.Table("instacat").IndexCreate("place", r.IndexCreateOpts{Geo: true}).Run(session)
log.Println("Create index place.")
}
示例12: initializeDB
func initializeDB() {
var err error
session, err = gorethink.Connect(gorethink.ConnectOpts{Address: config.DBHost, Database: config.DBName})
if err != nil {
logrus.Fatal("db:", err)
}
}
示例13: Setup
func (c *DBConfig) Setup() *DBSession {
if addr := os.Getenv(dbAddressEnv); addr != "" {
c.Address = addr
}
if name := os.Getenv(dbNameEnv); name != "" {
c.Name = name
}
if table := os.Getenv(gameTableEnv); table != "" {
c.GameTable = table
}
sess, err := r.Connect(r.ConnectOpts{
Address: c.Address,
Database: c.Name,
})
if err != nil {
log.Fatalf("RethinkDB Connection error: %s\n", err.Error())
}
// set session in DBConfig
dbs := &DBSession{S: sess, Config: *c}
// ensure named gameTable exists in database ...
dbs.CreateTable(c.GameTable)
// ... with the correct indexes
dbs.CreateIndexes(c.GameTable, c.Indexes)
return dbs
}
示例14: main
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.Parse()
// Connect to RethinkDB
var err error
session, err = r.Connect(r.ConnectOpts{
Address: *rethinkAddress,
})
if err != nil {
log.Fatal(err)
}
// Create the database and tables
r.DbCreate(*rethinkName).Exec(session)
r.Db(*rethinkName).TableCreate("invites").Exec(session)
r.Db(*rethinkName).Table("invites").IndexCreate("email").Exec(session)
r.Db(*rethinkName).Table("invites").IndexCreate("name").Exec(session)
// Add a CORS middleware
goji.Use(cors.New(cors.Options{
AllowCredentials: true,
}).Handler)
// Add routes to goji
goji.Get("/", index)
goji.Post("/check", check)
goji.Post("/free", free)
goji.Post("/create", create)
// Start the server
goji.Serve()
}
示例15: initdb
func initdb() {
// retries
for i := 0; i < 5; i++ {
s, err := rethink.Connect(rethink.ConnectOpts{
Address: dbAddr,
Database: dbName,
})
if err != nil {
log.Printf("unable to connect; retrying: %s", err)
time.Sleep(2 * time.Second)
continue
}
session = s
}
if session == nil {
log.Fatalf("unable to get database connection")
}
// Create database
rethink.DBCreate(dbName).Run(session)
// Check if table exists
_, err := rethink.Table(tblVisits).Run(session)
if err != nil {
// If not, create it
if _, err = rethink.DB(dbName).TableCreate(tblVisits).Run(session); err != nil {
log.Fatalf("error creating table: %s", err)
}
}
}