• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang redis.DialTimeout函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: TestReadDeadline

func TestReadDeadline(t *testing.T) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("net.Listen returned %v", err)
	}
	defer l.Close()

	go func() {
		for {
			c, err := l.Accept()
			if err != nil {
				return
			}
			go func() {
				time.Sleep(time.Second)
				c.Write([]byte("+OK\r\n"))
				c.Close()
			}()
		}
	}()

	c1, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0)
	if err != nil {
		t.Fatalf("redis.Dial returned %v", err)
	}
	defer c1.Close()

	_, err = c1.Do("PING")
	if err == nil {
		t.Fatalf("c1.Do() returned nil, expect error")
	}
	if c1.Err() == nil {
		t.Fatalf("c1.Err() = nil, expect error")
	}

	c2, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0)
	if err != nil {
		t.Fatalf("redis.Dial returned %v", err)
	}
	defer c2.Close()

	c2.Send("PING")
	c2.Flush()
	_, err = c2.Receive()
	if err == nil {
		t.Fatalf("c2.Receive() returned nil, expect error")
	}
	if c2.Err() == nil {
		t.Fatalf("c2.Err() = nil, expect error")
	}
}
开发者ID:JesseObrien,项目名称:redigo,代码行数:51,代码来源:conn_test.go


示例2: NewRedisCache

//创建一个新的redis连接
func NewRedisCache(ip string, port string, password string) (*RedisCache, error) {
	var (
		c   redis.Conn
		err error
	)

	c, err = redis.DialTimeout("tcp", ip+":"+port, 0, 1*time.Second, 1*time.Second)
	if err != nil {
		glog.Error("Error:", err)
		return nil, err
	}

	if password != "" {
		_, err = c.Do("AUTH", password)
		if err != nil {
			c.Close()
			glog.Error("Error:", err)
			return nil, err
		}
	}

	return &RedisCache{
		session: c,
	}, err
}
开发者ID:nprog,项目名称:IntelligentEngine,代码行数:26,代码来源:redis.go


示例3: NewRedisCache

// until redigo supports sharding/clustering, only one host will be in hostList
func NewRedisCache(host string, password string, defaultExpiration time.Duration) RedisCache {
	var pool = &redis.Pool{
		MaxIdle:     5,
		IdleTimeout: 120 * time.Second,
		Dial: func() (redis.Conn, error) {
			protocol := "tcp"
			c, err := redis.DialTimeout(protocol, host, 1*time.Second, 1*time.Second, 1*time.Second)
			if err != nil {
				return nil, err
			}

			// check with PING
			if _, err := c.Do("PING"); err != nil {
				c.Close()
				return nil, err
			}

			return c, err
		},
		// custom connection test method
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if _, err := c.Do("PING"); err != nil {
				return err
			}
			return nil
		},
	}
	return RedisCache{pool, defaultExpiration}
}
开发者ID:going,项目名称:cache,代码行数:30,代码来源:redis.go


示例4: main

func main() {
	Pool = &redis.Pool{
		MaxActive:   1000,
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			d, _ := time.ParseDuration("250ms")
			c, err := redis.DialTimeout("tcp", *redisServer, d, d, d)
			if err != nil {
				log.Println("Redis: connection error")
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}

	http.Handle("/", &RedirHttpHandler{})
	http.ListenAndServe(*httpPort, nil)

	log.Println("end main")
}
开发者ID:nordicdyno,项目名称:gourlmapper,代码行数:25,代码来源:main.go


示例5: initRedisQueue

func initRedisQueue(option *config.Option) map[string][]*poolwrapper {
	redispool := make(map[string][]*poolwrapper, 0)

	//创建redis的消费连接
	for _, v := range option.QueueHostPorts {

		hp := v
		pool := redis.NewPool(func() (conn redis.Conn, err error) {
			conn, err = redis.DialTimeout("tcp", hp.Host+":"+strconv.Itoa(hp.Port),
				time.Duration(hp.Timeout)*time.Second,
				time.Duration(hp.Timeout)*time.Second,
				time.Duration(hp.Timeout)*time.Second)

			return
		}, hp.Maxconn/2)

		pools, ok := redispool[v.QueueName]
		if !ok {
			pools = make([]*poolwrapper, 0)
			redispool[v.QueueName] = pools
		}

		poolw := &poolwrapper{}
		poolw.hostport = v.HostPort
		poolw.rpool = pool
		redispool[v.QueueName] = append(pools, poolw)
	}

	return redispool
}
开发者ID:sanbit,项目名称:flume-bridge,代码行数:30,代码来源:log_source_manager.go


示例6: open

func open(addr string) (redis.Conn, error) {
	return redis.DialTimeout("tcp",
		addr,
		1*time.Second,
		1*time.Second,
		1*time.Second)
}
开发者ID:shaovie,项目名称:go,代码行数:7,代码来源:mc.go


示例7: makeConn

func makeConn(addr, pwd string) (conn *redisConn, err error) {
	log.Info("makeConn|%v|%v", addr, pwd)
	conn = nil
	const dataTimeout = 5 * time.Second
	const connTimeout = 2 * time.Second
	var c redis.Conn
	if c, err = redis.DialTimeout("tcp", addr, connTimeout, dataTimeout, dataTimeout); err != nil {
		log.Error("makeConn|DialTimeout|%v", err)
		return
	}
	if pwd != "" {
		if _, err = c.Do("AUTH", pwd); err != nil {
			log.Error("makeConn|auth|%v", err)
			c.Close()
			return
		}
	}
	if _, err = c.Do("get", "__test"); err != nil {
		log.Error("makeConn|get|%v", err)
		c.Close()
		return
	}
	log.Info("makeConn|ok|%v", addr)
	var now = time.Now().Unix()
	conn = &redisConn{c, addr, seed, now + pingInterval, now}
	seed++
	return
}
开发者ID:shitfSign,项目名称:redis-4,代码行数:28,代码来源:redis.go


示例8: SlotsInfo

func SlotsInfo(addr string, fromSlot, toSlot int) (map[int]int, error) {
	c, err := redis.DialTimeout("tcp", addr, defaultTimeout, defaultTimeout, defaultTimeout)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer c.Close()

	infos, err := redis.Values(c.Do("SLOTSINFO", fromSlot, toSlot-fromSlot+1))
	if err != nil {
		return nil, errors.Trace(err)
	}

	slots := make(map[int]int)
	if infos != nil {
		for i := 0; i < len(infos); i++ {
			info, err := redis.Values(infos[i], nil)
			if err != nil {
				return nil, errors.Trace(err)
			}
			var slotid, slotsize int
			if _, err := redis.Scan(info, &slotid, &slotsize); err != nil {
				return nil, errors.Trace(err)
			} else {
				slots[slotid] = slotsize
			}
		}
	}
	return slots, nil
}
开发者ID:cookiebus,项目名称:codis,代码行数:29,代码来源:redis.go


示例9: msetTestSingle

func msetTestSingle(ch chan bool, cn, n int) error {
	var err error
	addr := utils.Addrcat(host, port)
	conn, err := redis.DialTimeout("tcp", addr, 0, 1*time.Second, 1*time.Second)
	if err != nil {
		log.Printf("redis conn error: %s", err)
		return err
	}
	defer conn.Close()
	v := make([]byte, dataSize)
	b := make([]interface{}, bucket+1)
	b[0] = topicName
	for i := 1; i < bucket+1; i++ {
		b[i] = v
	}
	count := n / bucket
	for i := 0; i < count; i++ {
		start := time.Now()
		_, err = conn.Do("MSET", b...)
		if err != nil {
			log.Printf("set error: c%d %v", cn, err)
		} else {
			end := time.Now()
			duration := end.Sub(start).Seconds()
			log.Printf("set succ: %s spend: %.3fms", topicName, duration*1000)
		}
	}
	ch <- true
	return nil
}
开发者ID:henser123,项目名称:uq,代码行数:30,代码来源:redis_bench.go


示例10: NewRedisRegistryWithConfig

func NewRedisRegistryWithConfig(conf *RedisConfig) (registry Registry) {
	pool := &redis.Pool{
		MaxIdle:     conf.MaxIdle,
		IdleTimeout: time.Duration(conf.IdleTimeoutS) * time.Second,
		MaxActive:   conf.MaxActive,
		Dial: func() (redis.Conn, error) {
			var c redis.Conn
			var err error
			c, err = redis.DialTimeout("tcp", conf.Address,
				time.Duration(conf.ConnectTimeoutMs)*time.Millisecond,
				time.Duration(conf.ReadTimeoutMs)*time.Millisecond,
				time.Duration(conf.WriteTimeoutMs)*time.Millisecond)
			if err != nil {
				return nil, err
			}
			//password authentication
			if len(conf.Password) > 0 {
				if _, err_pass := c.Do("AUTH", conf.Password); err_pass != nil {
					c.Close()
				}
			}
			return c, err
		},
	}
	return &redisRegistry{pool}
}
开发者ID:allenma,项目名称:gosoa,代码行数:26,代码来源:redis.go


示例11: getTestSingle

func getTestSingle(ch chan bool, cn, n int) error {
	addr := utils.Addrcat(host, port)
	conn, err := redis.DialTimeout("tcp", addr, 0, 1*time.Second, 1*time.Second)
	if err != nil {
		log.Printf("redis conn error: %s", err)
		return err
	}
	defer conn.Close()
	key := topicName + "/" + lineName
	for i := 0; i < n; i++ {
		start := time.Now()
		reply, err := conn.Do("GET", key)
		if err != nil {
			log.Printf("get error: c%d %v", cn, err)
		} else {
			rpl, err := redis.Strings(reply, err)
			if err != nil {
				fmt.Printf("redis.values error: c%d %v\n", cn, err)
				return err
			}
			// fmt.Printf("redis.strings %v\n", v)
			end := time.Now()
			duration := end.Sub(start).Seconds()
			id := rpl[1]
			log.Printf("get succ: %s spend: %.3fms", id, duration*1000)
		}
	}
	ch <- true
	return nil
}
开发者ID:henser123,项目名称:uq,代码行数:30,代码来源:redis_bench.go


示例12: get

func (p *connectionPool) get() (redis.Conn, error) {
	p.mu.Lock()
	for {
		available := len(p.available)
		switch {
		case available <= 0 && p.outstanding >= p.max:
			// Worst case. No connection available, and we can't dial a new one.
			p.co.Wait() // TODO starvation is possible here

		case available <= 0 && p.outstanding < p.max:
			// No connection available, but we can dial a new one.
			//
			// We shouldn't wait for a connection to be successfully established
			// before incrementing our outstanding counter, because additional
			// goroutines may sneak in with a get() request while we're dialing,
			// and bump outstanding above p.max.
			//
			// So, clients of get() should always put() the resulting conn, even
			// if it is nil. put() must handle that circumstance.
			p.outstanding++
			p.mu.Unlock()
			return redis.DialTimeout("tcp", p.address, p.connect, p.read, p.write)

		case available > 0:
			// Best case. We can directly use an available connection.
			var conn redis.Conn
			conn, p.available = p.available[0], p.available[1:]
			if p.outstanding < p.max {
				p.outstanding++
			}
			p.mu.Unlock()
			return conn, nil
		}
	}
}
开发者ID:Greentor,项目名称:roshi,代码行数:35,代码来源:connection_pool.go


示例13: NewRDBpool

// Redis DB Pool
func NewRDBpool(address string) *RDBpool {
	pool := redis.Pool{
		MaxActive: 0,
		MaxIdle:   3,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialTimeout(
				"tcp",
				address,
				time.Duration(1)*time.Second,
				time.Duration(1)*time.Second,
				time.Duration(1)*time.Second,
			)
			if err != nil {
				return nil, err
			}

			return c, err
		},
	}

	conn := pool.Get()
	defer conn.Close()
	if conn.Err() != nil {
		panic(fmt.Sprintf("Can not connect to redis %s", address))
	}

	return &RDBpool{pool: pool}
}
开发者ID:zhanghjster,项目名称:ChatChat,代码行数:29,代码来源:redis.go


示例14: doCommand

func (n *Node) doCommand(cmd string, args ...interface{}) (interface{}, error) {
	var err error
	var v interface{}
	for i := 0; i < 3; i++ {
		if n.conn == nil {
			n.conn, err = redis.DialTimeout("tcp", n.Addr, 5*time.Second, 0, 0)
			if err != nil {
				log.Errorf("dial %s error: %v, try again", n.Addr, err)
				continue
			}

		}

		v, err = n.conn.Do(cmd, args...)
		if err != nil {
			log.Errorf("do %s command for %s error: %v, try again", cmd, n.Addr, err)
			n.conn.Close()
			n.conn = nil
			continue
		} else {
			return v, nil
		}
	}

	// go here means do command error, maybe redis is down.
	return nil, err
}
开发者ID:no2key,项目名称:redis-failover,代码行数:27,代码来源:group.go


示例15: GetRedisStat

func GetRedisStat(addr string) (map[string]string, error) {
	c, err := redis.DialTimeout("tcp", addr, defaultTimeout, defaultTimeout, defaultTimeout)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer c.Close()

	ret, err := redis.String(c.Do("INFO"))
	if err != nil {
		return nil, errors.Trace(err)
	}
	m := make(map[string]string)
	lines := strings.Split(ret, "\n")
	for _, line := range lines {
		kv := strings.SplitN(line, ":", 2)
		if len(kv) == 2 {
			k, v := strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
			m[k] = v
		}
	}

	reply, err := redis.Strings(c.Do("config", "get", "maxmemory"))
	if err != nil {
		return nil, errors.Trace(err)
	}
	// we got result
	if len(reply) == 2 {
		if reply[1] != "0" {
			m["maxmemory"] = reply[1]
		} else {
			m["maxmemory"] = "∞"
		}
	}
	return m, nil
}
开发者ID:cookiebus,项目名称:codis,代码行数:35,代码来源:redis.go


示例16: SetupDbs

// SetupDbs takes connection parameters for redis and mongo and returns active sessions.
// The caller is responsible for closing the returned connections.
func SetupDbs(mongoURL, redisURL string) (*mgo.Database, redis.Conn, error) {
	mongoSession, err := mgo.Dial(mongoURL)
	if err != nil {
		return nil, nil, err
	}
	// use 'monotonic' consistency mode.  Since we only do reads, this doesn't have an actual effect
	// other than letting us read from secondaries if the connection string has the ?connect=direct param.
	mongoSession.SetMode(mgo.Monotonic, false)

	// empty db string uses the db from the connection url
	mongoDB := mongoSession.DB("")
	logger.Info("Connected to mongo", logger.M{"mongo_url": mongoURL})

	redisURL, err = resolveRedis(redisURL)
	if err != nil {
		return nil, nil, err
	}

	redisConn, err := redis.DialTimeout("tcp", redisURL, 15*time.Second, 10*time.Second, 10*time.Second)
	if err != nil {
		return nil, nil, err
	}
	logger.Info("Connected to redis", logger.M{"redis_url": redisURL})
	return mongoDB, redisConn, nil
}
开发者ID:bgveenstra,项目名称:moredis,代码行数:27,代码来源:dbs.go


示例17: NewRedisCache

// until redigo supports sharding/clustering, only one host will be in hostList
func NewRedisCache(host string, idle, max int, toc, tor, tow, defaultExpiration time.Duration) RedisCache {
	var pool = &redis.Pool{
		MaxIdle:     idle,
		MaxActive:   max,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialTimeout("tcp", host, toc, tor, tow)
			if err != nil {
				return nil, err
			}
			// check with PING
			if _, err := c.Do("PING"); err != nil {
				c.Close()
				return nil, err
			}
			return c, err
		},
		// custom connection test method
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if _, err := c.Do("PING"); err != nil {
				return err
			}
			return nil
		},
	}
	return RedisCache{pool, defaultExpiration}
}
开发者ID:huangjiasingle,项目名称:cache,代码行数:28,代码来源:redis.go


示例18: initConnPool

// create new connection pool to redis.
func (rc *RedisCli) initConnPool(conf *RedisConf) {
	if rc.dialFunc == nil {
		rc.dialFunc = func() (c redis.Conn, err error) {
			c, err = redis.DialTimeout("tcp", conf.Addr, conf.Timeout, conf.Timeout, conf.Timeout)
			if err != nil {
				return nil, err
			}
			if conf.Password != "" {
				if _, err := c.Do("AUTH", conf.Password); err != nil {
					c.Close()
					return nil, err
				}
			}
			_, selecterr := c.Do("SELECT", conf.DbNo)
			if selecterr != nil {
				c.Close()
				return nil, selecterr
			}
			return
		}
	}

	// initialize a new pool
	rc.p = &redis.Pool{
		MaxIdle:     MaxRedisIdleConn,
		IdleTimeout: 180 * time.Second,
		Dial:        rc.dialFunc,
	}
}
开发者ID:RivenZoo,项目名称:goutil,代码行数:30,代码来源:client.go


示例19: Dial

// Dial dials the local Redis server and selects database 9. To prevent
// stomping on real data, DialTestDB fails if database 9 contains data. The
// returned connection flushes database 9 on close.
func Dial() (redis.Conn, error) {
	c, err := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)
	if err != nil {
		return nil, err
	}

	_, err = c.Do("SELECT", "9")
	if err != nil {
		c.Close()
		return nil, err
	}

	n, err := redis.Int(c.Do("DBSIZE"))
	if err != nil {
		c.Close()
		return nil, err
	}

	if n != 0 {
		c.Close()
		return nil, errors.New("database #9 is not empty, test can not continue")
	}

	return testConn{c}, nil
}
开发者ID:CNDonny,项目名称:scope,代码行数:28,代码来源:testdb.go


示例20: sender

func sender(conn net.Conn) {
	redis_conn, _ := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)

	for {
		lang, _ := redis.String(redis_conn.Do("LPOP", "lang"))

		if lang != "" {
			words := lang
			if words[0] == 48 {
				os.Exit(0)
			} else {
				conn.Write(protocol.Packet([]byte(words)))
				fmt.Println(conn)

			}
		}

		// reader := bufio.NewReader(os.Stdin)
		// words, _, _ := reader.ReadLine()

		// words := "{\"Id\":1,\"Name\":\"golang\",\"Message\":\"message\"}"

	}
	fmt.Println("send over")
}
开发者ID:songqii,项目名称:git_-practice,代码行数:25,代码来源:client.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang redis.DialURL函数代码示例发布时间:2022-05-23
下一篇:
Golang redis.DialTestDB函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap