当前位置: 首页>>代码示例>>Golang>>正文


Golang mgo.DialWithInfo函数代码示例

本文整理汇总了Golang中labix/org/v2/mgo.DialWithInfo函数的典型用法代码示例。如果您正苦于以下问题:Golang DialWithInfo函数的具体用法?Golang DialWithInfo怎么用?Golang DialWithInfo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DialWithInfo函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: _createSession

//private to this file
func _createSession() (*mgo.Session, error) {

	if _cfg == nil {
		_cfg = &mongoConfig{}
		framework.Config.ReadInto("mongo", &_cfg)
	}

	var timeout = 10 * time.Second

	if _cfg.ConnectionString != "" {

		return mgo.DialWithTimeout(_cfg.ConnectionString, timeout)
	} else {

		dialInfo := mgo.DialInfo{}
		dialInfo.Database = _cfg.Database
		dialInfo.Username = _cfg.User
		dialInfo.Password = _cfg.Password
		dialInfo.Addrs = []string{fmt.Sprintf("%s:%s", _cfg.Host, _cfg.Port)}
		dialInfo.Timeout = timeout

		fmt.Println("Logging to", dialInfo.Addrs[0])

		return mgo.DialWithInfo(&dialInfo)
	}
}
开发者ID:mfelicio,项目名称:go-einvite-traditional,代码行数:27,代码来源:dbsession.go

示例2: mongoWorker

func (a *agent) mongoWorker() (worker.Worker, error) {
	dialInfo := gitjujutesting.MgoDialInfo(coretesting.Certs, a.hostPort)
	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		return nil, err
	}
	mc := &mongoConn{
		localHostPort: a.hostPort,
		session:       session,
	}
	runner := worker.NewRunner(
		connectionIsFatal(mc),
		func(err0, err1 error) bool { return true },
	)
	singularRunner, err := singular.New(runner, mc)
	if err != nil {
		return nil, fmt.Errorf("cannot start singular runner: %v", err)
	}
	a.notify.workerConnected()
	singularRunner.StartWorker(fmt.Sprint("worker-", a.notify.id), func() (worker.Worker, error) {
		return worker.NewSimpleWorker(func(stop <-chan struct{}) error {
			return a.worker(session, stop)
		}), nil
	})
	return runner, nil
}
开发者ID:klyachin,项目名称:juju,代码行数:26,代码来源:mongo_test.go

示例3: TestSetAdminMongoPassword

func (s *adminSuite) TestSetAdminMongoPassword(c *gc.C) {
	dialInfo := s.setUpMongo(c)
	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()
	admin := session.DB("admin")

	// Check that we can SetAdminMongoPassword to nothing when there's
	// no password currently set.
	err = mongo.SetAdminMongoPassword(session, "admin", "")
	c.Assert(err, gc.IsNil)

	err = mongo.SetAdminMongoPassword(session, "admin", "foo")
	c.Assert(err, gc.IsNil)
	err = admin.Login("admin", "")
	c.Assert(err, gc.ErrorMatches, "auth fails")
	err = admin.Login("admin", "foo")
	c.Assert(err, gc.IsNil)
	checkRoles(c, admin, "admin",
		[]interface{}{
			string(mgo.RoleReadWriteAny),
			string(mgo.RoleDBAdminAny),
			string(mgo.RoleUserAdminAny),
			string(mgo.RoleClusterAdmin)})
}
开发者ID:jimmiebtlr,项目名称:juju,代码行数:25,代码来源:admin_test.go

示例4: changeVotes

func changeVotes(c *gc.C, insts []*gitjujutesting.MgoInstance, voteId int) {
	c.Logf("changing voting id to %v", voteId)

	addrs := make([]string, len(insts))
	for i, inst := range insts {
		addrs[i] = inst.Addr()
	}
	dialInfo := gitjujutesting.MgoDialInfo(coretesting.Certs, addrs...)

	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()

	members, err := replicaset.CurrentMembers(session)
	c.Assert(err, gc.IsNil)
	c.Assert(members, gc.HasLen, len(insts))
	for i := range members {
		member := &members[i]
		if member.Id == voteId {
			member.Priority = nil
		} else {
			member.Priority = newFloat64(0.1)
		}
	}
	c.Logf("new member set: %#v", members)
	err = replicaset.Set(session, members)
	c.Assert(err, gc.IsNil)

	c.Logf("successfully changed replica set members")
}
开发者ID:klyachin,项目名称:juju,代码行数:30,代码来源:mongo_test.go

示例5: TestCustomDial

func (s *S) TestCustomDial(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr net.Addr) (net.Conn, error) {
		tcpaddr, ok := addr.(*net.TCPAddr)
		if !ok {
			return nil, fmt.Errorf("unexpected address type: %T", addr)
		}
		dials <- true
		return net.DialTCP("tcp", nil, tcpaddr)
	}
	info := mgo.DialInfo{
		Addrs: []string{"localhost:40012"},
		Dial:  dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
开发者ID:cespare,项目名称:prat,代码行数:34,代码来源:cluster_test.go

示例6: Open

// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
//
// A policy may be provided, which will be used to validate and
// modify behaviour of certain operations in state. A nil policy
// may be provided.
//
// Open returns unauthorizedError if access is unauthorized.
func Open(info *Info, opts mongo.DialOpts, policy Policy) (*State, error) {
	logger.Infof("opening state, mongo addresses: %q; entity %q", info.Addrs, info.Tag)
	di, err := mongo.DialInfo(info.Info, opts)
	if err != nil {
		return nil, err
	}
	logger.Debugf("dialing mongo")
	session, err := mgo.DialWithInfo(di)
	if err != nil {
		return nil, err
	}
	logger.Debugf("connection established")

	_, err = replicaset.CurrentConfig(session)
	safe := &mgo.Safe{J: true}
	if err == nil {
		// set mongo to write-majority (writes only returned after replicated
		// to a majority of replica-set members)
		safe.WMode = "majority"
	}
	session.SetSafe(safe)

	st, err := newState(session, info, policy)
	if err != nil {
		session.Close()
		return nil, err
	}
	session.SetSocketTimeout(mongo.SocketTimeout)
	return st, nil
}
开发者ID:rogpeppe,项目名称:juju,代码行数:39,代码来源:open.go

示例7: MustDial

// MustDial returns a new connection to the MongoDB server, and panics on
// errors.
func (inst *MgoInstance) MustDial() *mgo.Session {
	s, err := mgo.DialWithInfo(inst.DialInfo())
	if err != nil {
		panic(err)
	}
	return s
}
开发者ID:jkary,项目名称:core,代码行数:9,代码来源:mgo.go

示例8: attemptInitiateMongoServer

// attemptInitiateMongoServer attempts to initiate the replica set.
func attemptInitiateMongoServer(dialInfo *mgo.DialInfo, memberHostPort string) error {
	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		return fmt.Errorf("can't dial mongo to initiate replicaset: %v", err)
	}
	defer session.Close()
	session.SetSocketTimeout(mongo.SocketTimeout)

	var cfg *replicaset.Config
	cfg, err = replicaset.CurrentConfig(session)
	if err == nil && len(cfg.Members) > 0 {
		logger.Infof("replica set configuration already found: %#v", cfg)
		return nil
	}
	if err != nil && err != mgo.ErrNotFound {
		return fmt.Errorf("cannot get replica set configuration: %v", err)
	}
	return replicaset.Initiate(
		session,
		memberHostPort,
		mongo.ReplicaSetName,
		map[string]string{
			jujuMachineTag: agent.BootstrapMachineId,
		},
	)
}
开发者ID:jimmiebtlr,项目名称:juju,代码行数:27,代码来源:initiate.go

示例9: TestCustomDialNew

func (s *S) TestCustomDialNew(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr *mgo.ServerAddr) (net.Conn, error) {
		dials <- true
		if addr.TCPAddr().Port == 40012 {
			c.Check(addr.String(), Equals, "localhost:40012")
		}
		return net.DialTCP("tcp", nil, addr.TCPAddr())
	}
	info := mgo.DialInfo{
		Addrs:      []string{"localhost:40012"},
		DialServer: dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
开发者ID:davidsoloman,项目名称:beats,代码行数:33,代码来源:cluster_test.go

示例10: display

func display(w http.ResponseWriter, r *http.Request) {

	mongoDBDialInfo := &mgo.DialInfo{
		Addrs:    []string{MongoDBHosts},
		Database: AuthDatabase,
		Username: AuthUserName,
		Password: AuthPassword,
	}

	mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
	if err != nil {
		fmt.Println("error1")
	}

	mongoSession.SetMode(mgo.Monotonic, true)

	collection := mongoSession.DB(TestDatabase).C("AddressData")

	var result AddressData

	err = collection.Find(bson.M{"Name": r.FormValue("name")}).One(&result)

	if result.Email != "" {
		errn := displayTemplate.Execute(w, "The email id you wanted is: "+result.Email)
		if errn != nil {
			http.Error(w, errn.Error(), http.StatusInternalServerError)
		}
	} else {
		displayTemplate.Execute(w, "Sorry... The email id you wanted does not exist.")
	}
}
开发者ID:AllGoodPlanes,项目名称:DockerizeMongoApp,代码行数:31,代码来源:eAddress.go

示例11: Initialize

func (g *MongoGateway) Initialize() error {
	var connectionErr error
	if g.DialInfo == nil {
		g.InitDialInfo()
	}
	g.BaseSession, connectionErr = mgo.DialWithInfo(g.DialInfo)
	return connectionErr
}
开发者ID:repp,项目名称:armadillo,代码行数:8,代码来源:mongo_gateway.go

示例12: MaybeInitiateMongoServer

// MaybeInitiateMongoServer checks for an existing mongo configuration.
// If no existing configuration is found one is created using Initiate.
func MaybeInitiateMongoServer(p InitiateMongoParams) error {
	logger.Debugf("Initiating mongo replicaset; dialInfo %#v; memberHostport %q; user %q; password %q", p.DialInfo, p.MemberHostPort, p.User, p.Password)
	defer logger.Infof("finished MaybeInitiateMongoServer")

	if len(p.DialInfo.Addrs) > 1 {
		logger.Infof("more than one member; replica set must be already initiated")
		return nil
	}
	p.DialInfo.Direct = true

	// TODO(rog) remove this code when we no longer need to upgrade
	// from pre-HA-capable environments.
	if p.User != "" {
		p.DialInfo.Username = p.User
		p.DialInfo.Password = p.Password
	}

	session, err := mgo.DialWithInfo(p.DialInfo)
	if err != nil {
		return fmt.Errorf("can't dial mongo to initiate replicaset: %v", err)
	}
	defer session.Close()

	// Initiate may fail while mongo is initialising, so we retry until
	// we succssfully populate the replicaset config.
	for attempt := initiateAttemptStrategy.Start(); attempt.Next(); {
		var cfg *replicaset.Config
		cfg, err = replicaset.CurrentConfig(session)
		if err == nil && len(cfg.Members) > 0 {
			logger.Infof("replica set configuration already found: %#v", cfg)
			return nil
		}
		if err != nil && err != mgo.ErrNotFound {
			return fmt.Errorf("cannot get replica set configuration: %v", err)
		}
		err = replicaset.Initiate(
			session,
			p.MemberHostPort,
			mongo.ReplicaSetName,
			map[string]string{
				jujuMachineTag: agent.BootstrapMachineId,
			},
		)
		if err == nil {
			logger.Infof("replica set initiated")
			return nil
		}
		if attempt.HasNext() {
			logger.Debugf("replica set initiation failed, will retry: %v", err)
		}
		// Release sockets, which may have been closed by mgo.
		session.Refresh()
	}
	return fmt.Errorf("cannot initiate replica set: %v", err)
}
开发者ID:rogpeppe,项目名称:juju,代码行数:57,代码来源:initiate.go

示例13: main

func main() {
	results = make(chan *common.FileStat)
	commonStatMutex = make(chan int, 1)
	commonStat = new(common.FileStat)
	commonStat.Filename = "all"
	// Listen on TCP port 2000 on all interfaces.
	mongoSession, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs: []string{"localhost"}, Database: "gotest", Username: "gotest", Password: "GOLang123"})

	if err != nil {
		log.Fatalf("CreateSession: %s\n", err)
	}
	mongoSession.SetMode(mgo.Monotonic, true)
	log.Println("Start listen tcp on 8911")
	l, err := net.Listen("tcp", ":8911")
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()
	for {
		// Wait for a connection.
		conn, err := l.Accept()
		if err != nil {
			log.Fatal(err)
		}
		// Handle the connection in a new goroutine.
		// The loop then returns to accepting, so that
		// multiple connections may be served concurrently.
		go func(c net.Conn) {
			// Echo all incoming data.
			defer c.Close()
			info := new(common.FileStat)
			if err := info.Read(c); err != nil {
				log.Println(err)
				return
			}
			//			json_to_save := to_json(info)
			item_to_save := to_bson(info)
			commonStatMutex <- 1 // It will block next concurrent call
			conn.Write(commonStat.Bytes())
			<-commonStatMutex
			//			fmt.Println(json_to_save)
			//				client.Set('a', dat)
			// Shut down the connection.
			go func() {
				sessionCopy := mongoSession.Copy()
				defer sessionCopy.Close()
				// save received data to mongo sessionCopy
				collection := sessionCopy.DB("gotest").C("filestat")
				collection.Insert(item_to_save)
			}()

		}(conn)
	}
}
开发者ID:vvf,项目名称:gotest,代码行数:55,代码来源:server-saver.go

示例14: CreateSession

// CreateSession creates a connection pool for use
func CreateSession(sessionId string, mode string, sessionName string, hosts []string, databaseName string, username string, password string) (err error) {
	defer helper.CatchPanic(nil, sessionId, "CreateSession")

	tracelog.STARTEDf(sessionId, "CreateSession", "Mode[%s] SessionName[%s] Hosts[%s] DatabaseName[%s] Username[%s]", mode, sessionName, hosts, databaseName, username)

	// Create the database object
	mongoSession := &mongoSession{
		mongoDBDialInfo: &mgo.DialInfo{
			Addrs:    hosts,
			Timeout:  60 * time.Second,
			Database: databaseName,
			Username: username,
			Password: password,
		},
	}

	// Establish the master session
	mongoSession.mongoSession, err = mgo.DialWithInfo(mongoSession.mongoDBDialInfo)
	if err != nil {
		tracelog.COMPLETED_ERROR(err, sessionId, "CreateSession")
		return err
	}

	switch mode {
	case "strong":
		// Reads and writes will always be made to the master server using a
		// unique connection so that reads and writes are fully consistent,
		// ordered, and observing the most up-to-date data.
		// http://godoc.org/labix.org/v2/mgo#Session.SetMode
		mongoSession.mongoSession.SetMode(mgo.Strong, true)
		break

	case "monotonic":
		// Reads may not be entirely up-to-date, but they will always see the
		// history of changes moving forward, the data read will be consistent
		// across sequential queries in the same session, and modifications made
		// within the session will be observed in following queries (read-your-writes).
		// http://godoc.org/labix.org/v2/mgo#Session.SetMode
		mongoSession.mongoSession.SetMode(mgo.Monotonic, true)
	}

	// Have the session check for errors
	// http://godoc.org/labix.org/v2/mgo#Session.SetSafe
	mongoSession.mongoSession.SetSafe(&mgo.Safe{})

	// Add the database to the map
	_This.sessions[sessionName] = mongoSession

	tracelog.COMPLETED(sessionId, "CreateSession")
	return err
}
开发者ID:kelu95,项目名称:revel-mgo,代码行数:52,代码来源:mongo.go

示例15: TestFailFast

func (s *S) TestFailFast(c *C) {
	info := mgo.DialInfo{
		Addrs:    []string{"localhost:99999"},
		Timeout:  5 * time.Second,
		FailFast: true,
	}

	started := time.Now()

	_, err := mgo.DialWithInfo(&info)
	c.Assert(err, ErrorMatches, "no reachable servers")

	c.Assert(started.After(time.Now().Add(-time.Second)), Equals, true)
}
开发者ID:davidsoloman,项目名称:beats,代码行数:14,代码来源:cluster_test.go


注:本文中的labix/org/v2/mgo.DialWithInfo函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。