Пример #1
0
func (s *S) TestAddRouteCommandFailure(c *check.C) {
	r := hipacheRouter{prefix: "hipache", pool: redis.NewPool(fakeConnect, 5)}
	addr, _ := url.Parse("http://www.tsuru.io")
	err := r.AddBackend("tip")
	c.Assert(err, check.IsNil)
	conn = &FailingFakeRedisConn{}
	r2 := hipacheRouter{prefix: "hipache", pool: redis.NewPool(fakeConnect, 5)}
	err = r2.AddRoute("tip", addr)
	c.Assert(err, check.FitsTypeOf, &router.RouterError{})
	e, ok := err.(*router.RouterError)
	c.Assert(ok, check.Equals, true)
	c.Assert(e.Err.Error(), check.Equals, "I can't do that.")
	c.Assert(e.Op, check.Equals, "routes")
}
Пример #2
0
func NewStorage(server string) *Storage {
	pool := redis.NewPool(func() (conn redis.Conn, err error) {
		conn, err = redis.Dial("tcp", server)
		return
	}, 3)
	return &Storage{pool}
}
Пример #3
0
// Create a new connection pool given a host:port string.
// A password may be supplied as well, on the form "password@host:port".
func NewConnectionPoolHost(hostColonPort string) *ConnectionPool {
	// Create a redis Pool
	redisPool := redis.NewPool(
		// Anonymous function for calling new RedisConnectionTo with the host:port
		func() (redis.Conn, error) {
			conn, err := newRedisConnectionTo(hostColonPort)
			if err != nil {
				return nil, err
			}
			// If a password is given, use it to authenticate
			if password, _, ok := twoFields(hostColonPort, "@"); ok {
				if password != "" {
					if _, err := conn.Do("AUTH", password); err != nil {
						conn.Close()
						return nil, err
					}
				}
			}
			return conn, err
		},
		// Maximum number of idle connections to the redis database
		maxIdleConnections)
	pool := ConnectionPool(*redisPool)
	return &pool
}
Пример #4
0
func main() {
	// 4 reqs/hour
	rate, err := limiter.NewRateFromFormatted("4-H")
	if err != nil {
		panic(err)
	}

	// Create a Redis pool.
	pool := redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", ":6379")
		if err != nil {
			return nil, err
		}
		return c, err
	}, 100)

	// Create a store with the pool.
	store, err := limiter.NewRedisStore(pool, "limitergjrexample")
	if err != nil {
		panic(err)
	}

	mw := limiter.NewHTTPMiddleware(limiter.NewLimiter(store, rate))
	http.Handle("/", mw.Handler(http.HandlerFunc(index)))

	fmt.Println("Server is running on port 7777...")
	log.Fatal(http.ListenAndServe(":7777", nil))

}
Пример #5
0
func init() {
	max := maxConnection()
	url := address()
	redisPool = redis.NewPool(func() (redis.Conn, error) {
		return redisurl.ConnectToURL(url)
	}, max)
}
Пример #6
0
func main() {
	pool := redis.NewPool(func() (redis.Conn, error) {
		return redis.Dial("tcp", ":6379")
	}, 10)
	app := redisocket.NewApp(pool)

	err := make(chan error)
	go func() {
		err <- app.Listen()
	}()

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {

		sub, err := app.NewClient(w, r)
		if err != nil {
			log.Fatal("Client Connect Error")
			return
		}
		c := &User{app, sub}
		err = c.Listen()
		log.Println(err, "http point")
		return
	})

	go func() {
		err <- http.ListenAndServe(":8888", nil)
	}()
	select {
	case e := <-err:
		log.Println(e)
	}
}
Пример #7
0
func (this *RedisProvider) SessionInit(path string, gctime int) error {
	this.maxlifetime = gctime
	pathArr := strings.Split(path, ",")
	if len(pathArr) > 0 {
		this.path = pathArr[0]
	}
	if len(pathArr) > 1 {
		ps, err := strconv.Atoi(pathArr[1])
		if err != nil || ps <= 0 {
			this.poolsize = 200
		} else {
			this.poolsize = ps
		}
	} else {
		this.poolsize = 200
	}
	this.pools = redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", this.path)
		if err != nil {
			return nil, err
		}
		_, err = c.Do("SELECT", 0)
		if err != nil {
			c.Close()
			return nil, err
		}
		return c, nil
	}, this.poolsize)
	return this.pools.Get().Err()
}
Пример #8
0
//savepath like redisserveraddr,poolsize,password
//127.0.0.1:6379,100,astaxie
func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
	rp.maxlifetime = maxlifetime
	configs := strings.Split(savePath, ",")
	if len(configs) > 0 {
		rp.savePath = configs[0]
	}
	if len(configs) > 1 {
		poolsize, err := strconv.Atoi(configs[1])
		if err != nil || poolsize <= 0 {
			rp.poolsize = MAX_POOL_SIZE
		} else {
			rp.poolsize = poolsize
		}
	} else {
		rp.poolsize = MAX_POOL_SIZE
	}
	if len(configs) > 2 {
		rp.password = configs[2]
	}
	rp.poollist = redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", rp.savePath)
		if err != nil {
			return nil, err
		}
		if rp.password != "" {
			if _, err := c.Do("AUTH", rp.password); err != nil {
				c.Close()
				return nil, err
			}
		}
		return c, err
	}, rp.poolsize)
	return nil
}
Пример #9
0
func NewMessageServer(redisAddr string, fast bool) (http.Handler, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	m := &MessageServer{
		r:    mux.NewRouter(),
		name: strings.Replace(hostname, "linuxcon-demo-", "", -1),
		pool: redis.NewPool(func() (redis.Conn, error) {
			return redis.Dial("tcp", redisAddr)
		}, 10),
	}
	m.r.HandleFunc("/", m.getMessage).Methods("GET")
	m.r.HandleFunc("/cache", m.getCache).Methods("GET")
	// start filling the cache async on boot
	go m.fillCache(redisAddr, fast)
	go func() {
		for range time.Tick(3 * time.Second) {
			if _, err := m.do("SET", fmt.Sprintf("nodes.%s.avg", m.name), requests.Rate1()); err != nil {
				logrus.Error(err)
			}
		}
	}()
	return m, nil
}
Пример #10
0
// getPool returns a redis connection pool for a given address
func (p *Pool) getPool(addr string) *redis.Pool {

	defer scopedLock(&p.mutx)()

	pool, found := p.pools[addr]
	if !found {
		pool = redis.NewPool(func() (redis.Conn, error) {
			return p.dialFunc(addr)
		}, maxIdle)

		pool.TestOnBorrow = func(c redis.Conn, t time.Time) error {

			// for testing - count how many borrows we did
			p.numBorrowed++
			if time.Since(t) > testOnBorrowInterval {
				_, err := c.Do("PING")
				return err
			}
			return nil
		}

		p.pools[addr] = pool
	}

	return pool

}
Пример #11
0
func TestRedisStorageRemoveImagePrefixed(t *testing.T) {
	conn := resultCommandConn{
		fakeConn: &fakeConn{},
		reply:    map[string]interface{}{"DEL": int64(1)},
	}
	var storage redisStorage
	storage.pool = redis.NewPool(func() (redis.Conn, error) {
		return &conn, nil
	}, 3)
	storage.prefix = "cluster"
	image := "tsuru/python"
	err := storage.RemoveImage(image)
	if err != nil {
		t.Error(err)
	}
	cmd := conn.cmds[0]
	expectedCmd := "DEL"
	if cmd.cmd != expectedCmd {
		t.Errorf("RemoveImage(%q): want command %q. Got %q.", image, expectedCmd, cmd.cmd)
	}
	expectedArgs := []interface{}{"cluster:image:" + image}
	if !reflect.DeepEqual(cmd.args, expectedArgs) {
		t.Errorf("RemoveImage(%q): want args %#v. Got %#v.", image, expectedArgs, cmd.args)
	}
}
Пример #12
0
func NewRedisOption(host string, password string, size int, num int, life int64) (*RedisOption, error) {
	ro := &RedisOption{
		num:      num,
		size:     size,
		life:     life,
		host:     host,
		password: password,
	}
	ro.Pool = redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", ro.host)
		if err != nil {
			return nil, err
		}
		if ro.password != "" {
			if _, err := c.Do("AUTH", ro.password); err != nil {
				c.Close()
				return nil, err
			}
		}
		_, err = c.Do("SELECT", ro.num)
		if err != nil {
			c.Close()
			return nil, err
		}
		return c, err
	}, ro.size)
	err := ro.Pool.Get().Err()
	if err != nil {
		return nil, err
	}
	return ro, nil
}
Пример #13
0
func TestRedisStorageRetrieveContainer(t *testing.T) {
	conn := resultCommandConn{
		fakeConn: &fakeConn{},
		reply:    map[string]interface{}{"GET": []byte("server0")},
	}
	var storage redisStorage
	storage.pool = redis.NewPool(func() (redis.Conn, error) {
		return &conn, nil
	}, 3)
	container := "affe3022"
	host, err := storage.RetrieveContainer(container)
	if err != nil {
		t.Error(err)
	}
	expectedHost := "server0"
	if host != expectedHost {
		t.Errorf("RetrieveContainer(%q): want host %q. Got %q.", container, expectedHost, host)
	}
	cmd := conn.cmds[0]
	expectedCmd := "GET"
	if cmd.cmd != expectedCmd {
		t.Errorf("RetrieveContainer(%q): want command %q. Got %q.", container, expectedCmd, cmd.cmd)
	}
	expectedArgs := []interface{}{container}
	if !reflect.DeepEqual(cmd.args, expectedArgs) {
		t.Errorf("RetrieveContainer(%q): want args %#v. Got %#v.", container, expectedArgs, cmd.args)
	}
}
Пример #14
0
func (rb *Redisbeat) Setup(b *beat.Beat) error {
	rb.events = b.Publisher.Connect()
	rb.done = make(chan struct{})

	// Set up redis pool
	redisPool := redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial(rb.network, rb.host+":"+strconv.Itoa(rb.port))

		if err != nil {
			return nil, err
		}

		return c, err
	}, rb.maxConn)

	rb.redisPool = redisPool

	if rb.auth {
		c := rb.redisPool.Get()
		defer c.Close()

		authed, err := c.Do("AUTH", rb.pass)
		if err != nil {
			return err
		} else {
			logp.Debug("redisbeat", "AUTH %v", authed)
		}
	}

	return nil
}
Пример #15
0
func main() {

	rp = redis.NewPool(func() (redis.Conn, error) {
		return redis.Dial("tcp", RedisHost+":"+RedisPort)
	}, 1000)

	var url = DbUser + ":" + DbPass + "@tcp(" + DbHost + ":" + DbPort + ")/" + DbName
	db, _ = sql.Open("mysql", url)
	defer db.Close()

	// Clear Redis
	go func() {
		c := rp.Get()
		c.Do("FLUSHALL")
	}()
	go loadAllUser()
	go loadAllFood()

	router := httprouter.New()
	router.POST("/login", LoginController)
	router.GET("/foods", FoodController)
	router.POST("/carts", NewCartsController)
	router.PATCH("/carts/:cart_id", FoodsToCartController)
	router.POST("/orders", PlaceOrderController)
	router.GET("/orders", ShowOrdersController)
	router.GET("/admin/orders", AdminShowOrdersController)

	log.Fatal(http.ListenAndServe(AppHost+":"+AppPort, router))
}
Пример #16
0
// New makes and returns a pointer to a new Connector instance. It sets some
// defaults on the ConnectionParam object, such as the policy, which defaults to
// a LogReconnectPolicy with a base of 10ms. A call to this function does not
// produce a connection.
func New(param ConnectionParam, maxIdle int) (*redis.Pool, ReconnectPolicy) {
	if param.Policy == nil {
		param.Policy = &LogReconnectPolicy{Base: 10, Factor: time.Millisecond}
	}

	return redis.NewPool(connect(param), maxIdle), param.Policy
}
Пример #17
0
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
}
Пример #18
0
// NewAutocompleter creates a new Autocompleter with the given host and key name
func NewAutocompleter(addr, name string) *Autocompleter {
	return &Autocompleter{
		pool: redis.NewPool(func() (redis.Conn, error) {
			return redis.Dial("tcp", addr)
		}, maxConns),
		name: name,
	}
}
Пример #19
0
func NewRedisSender(port, channel string) Sender {
	return &redisSender{
		redis.NewPool(func() (redis.Conn, error) {
			return redis.Dial("tcp", port)
		}, 3),
		channel,
	}
}
Пример #20
0
func (this *Redis) Init() {
	this.pool = redis.NewPool(func() (redis.Conn, error) {
		return redis.Dial("tcp", config.GetConfig("redis_host"))
	}, 20)
	this.pool.IdleTimeout = 45 * time.Second
	this.pool.MaxActive = 30
	this.pool.MaxIdle = 30
}
Пример #21
0
func (s *RedismqSuite) SetUpSuite(c *gocheck.C) {
	s.pool = redis.NewPool(func() (redis.Conn, error) {
		return redis.Dial("tcp", "127.0.0.1:6379")
	}, 10)
	config.Set("queue", "redis")
	q := redismqQ{name: "default", pool: s.pool, prefix: "test", maxSize: 10}
	conn := s.pool.Get()
	conn.Do("DEL", q.key())
}
Пример #22
0
func NewPool(network, address string) *redis.Pool {
	return redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", address)
		if err != nil {
			return nil, err
		}
		return c, nil
	}, REDIS_POOL_SIZE)
}
Пример #23
0
func newRedisConnectionPool(host string, poolSize int) *redis.Pool {
	return redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", host)
		if err != nil {
			return nil, err
		}
		return c, err
	}, poolSize)
}
Пример #24
0
func newConnectionPool(connector Connector, size int) *redis.Pool {
	return redis.NewPool(func() (redis.Conn, error) {
		conn, err := connector.Connect()
		if err != nil {
			return nil, err
		}
		return redis.NewConn(conn, 0, 0), nil
	}, size)
}
Пример #25
0
// newRedisPool returns
func newRedisPool() *redis.Pool {
	return redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", ":6379")
		if err != nil {
			return nil, err
		}
		return c, err
	}, 100)
}
Пример #26
0
func InitCache() {
	pool = redis.NewPool(initConn, poolSize)
	conn := Open()
	defer conn.Close()
	pong, err := conn.Do("ping")
	if err != nil {
		log.Panicln("can't connect cache server has error", err)
	}
	log.Println("reach cache server ", pong)
}
Пример #27
0
func TestRedisRemoveContainerFailure(t *testing.T) {
	var conn failingFakeConn
	var storage redisStorage
	storage.pool = redis.NewPool(func() (redis.Conn, error) {
		return &conn, nil
	}, 3)
	err := storage.RemoveContainer("affe3022")
	if err == nil {
		t.Error("Unexpected <nil> error")
	}
}
Пример #28
0
func init() {
	var err error
	if pool, err = Open("127.0.0.1:6379", 10, 5, time.Duration(10)*time.Second); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fn := func() (redigo.Conn, error) {
		return redigo.Dial("tcp4", "127.0.0.1:6379")
	}
	pool1 = redigo.NewPool(fn, 5)
}
Пример #29
0
func newRedisPool(uri string, maxIdle int, maxOpen int, idleTimout time.Duration) *redis.Pool {
	generator := func() (redis.Conn, error) {
		return redisurl.ConnectToURL(uri)
	}

	p := redis.NewPool(generator, maxIdle)
	p.MaxActive = maxOpen
	p.IdleTimeout = idleTimout

	return p
}
Пример #30
0
func connect() redis.Conn {
	if pool == nil {
		srv, err := config.GetString("hipache:redis-server")
		if err != nil {
			srv = "localhost:6379"
		}
		pool = redis.NewPool(func() (redis.Conn, error) {
			return redis.Dial("tcp", srv)
		}, 10)
	}
	return pool.Get()
}