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

Golang redis.Client类代码示例

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

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



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

示例1: authenticateByPassword

func authenticateByPassword(c *redis.Client, password string) error {
	if r := c.Cmd("AUTH", password); r.Err != nil {
		logger.Errorf("Faild to authenticate. %s", r.Err)
		return r.Err
	}
	return nil
}
开发者ID:supercaracal,项目名称:mackerel-agent-plugins,代码行数:7,代码来源:redis.go


示例2: SpawnAsteroid

func (u *Universe) SpawnAsteroid(redis_client *redis.Client) {
	if rand.Float32() < 0.1 {
		live_asteroids := redis_client.Cmd("KEYS", "asteroid-*")
		num_asteroids := 1000
		if len(live_asteroids.Elems) < num_asteroids {

			temp_asteroid := &asteroid.Asteroid{gameobject.GameObject{
				Id:   rand.Intn(500000),
				X:    rand.Float64(),
				Y:    rand.Float64(),
				Velx: rand.Float64() * 100,
				Vely: rand.Float64() * 100},
				100}

			u.Asteroids = append(u.Asteroids, temp_asteroid)
			asteroid_json, _ := json.Marshal(temp_asteroid)

			redis_client.Cmd("SET", fmt.Sprintf("asteroid-%v", temp_asteroid.Id), asteroid_json)
		}

		// temp_bullet := &bullet.Bullet{gameobject.GameObject{
		//                     Id: rand.Intn(500000),
		//                     X: rand.Float64(),
		//                     Y: rand.Float64(),
		//                     Velx: rand.Float64() * 100,
		//                     Vely: rand.Float64() * 100},
		//                     100}

		// u.Bullets = append(u.Bullets,temp_bullet)

		// redis_client.Cmd("SET", fmt.Sprintf("bullet-%v", temp_bullet.Id), temp_bullet)

	}
}
开发者ID:cleblanc87,项目名称:asteroids-go-server,代码行数:34,代码来源:universe.go


示例3: fetchPercentageOfMemory

func fetchPercentageOfMemory(c *redis.Client, stat map[string]float64) error {
	r := c.Cmd("CONFIG", "GET", "maxmemory")
	if r.Err != nil {
		logger.Errorf("Failed to run `CONFIG GET maxmemory` command. %s", r.Err)
		return r.Err
	}

	res, err := r.Hash()
	if err != nil {
		logger.Errorf("Failed to fetch maxmemory. %s", err)
		return err
	}

	maxsize, err := strconv.ParseFloat(res["maxmemory"], 64)
	if err != nil {
		logger.Errorf("Failed to parse maxmemory. %s", err)
		return err
	}

	if maxsize == 0.0 {
		stat["percentage_of_memory"] = 0.0
	} else {
		stat["percentage_of_memory"] = 100.0 * stat["used_memory"] / maxsize
	}

	return nil
}
开发者ID:y-kuno,项目名称:mackerel-agent-plugins,代码行数:27,代码来源:redis.go


示例4: getBackend

func getBackend(hostname string, defaultBackendType string, redisClient *redis.Client) (string, error) {
	fmt.Println("Looking up", hostname)

	backends, error := redisClient.Cmd("smembers", "hostnames:"+hostname+":backends").List()
	if error != nil {
		fmt.Println("Error in redis lookup for hostname backend", error)
		return "", error
	}

	if len(backends) == 0 {
		backends, error = redisClient.Cmd("smembers", "hostnames:"+defaultBackendType+":backends").List()
		if error != nil {
			fmt.Println("Error in redis lookup for default backend", error)
			return "", error
		}
		if len(backends) == 0 {
			fmt.Println("No default backend of type", defaultBackendType)
			return "", errors.New("Could not find default backend of type " + defaultBackendType)
		}
	}

	fmt.Println("Found backends:", backends)
	backend := backends[int(rand.Float32()*float32(len(backends)))]
	return backend, nil
}
开发者ID:postfix,项目名称:stupid-proxy,代码行数:25,代码来源:proxy.go


示例5: getRedisInfo

func getRedisInfo(c *redis.Client) (*map[string]string, error) {
	info := make(map[string]string)

	r := c.Cmd("info")
	if r.Err != nil {
		return nil, errors.New("couldn't execute query")
	}
	str, err := r.Str()
	if err != nil {
		return nil, errors.New("couldn't execute query")
	}

	for _, line := range strings.Split(str, "\r\n") {
		if line == "" {
			continue
		}
		if re, _ := regexp.MatchString("^#", line); re {
			continue
		}

		record := strings.SplitN(line, ":", 2)
		if len(record) < 2 {
			continue
		}
		key, value := record[0], record[1]
		info[key] = value
	}

	return &info, nil
}
开发者ID:hiroakis,项目名称:go-check-plugins,代码行数:30,代码来源:check-redis.go


示例6: SetRedisValue

func SetRedisValue(redisClient *redis.Client, key string, value string) {
	var reply *redis.Reply = redisClient.Cmd("SET", key, value)

	if reply.Err != nil {
		panic(reply.Err)
	}
}
开发者ID:jansichermann,项目名称:redisinterface,代码行数:7,代码来源:redisinterface.go


示例7: list

func list(connection *redis.Client) map[string][]string {
	var blacklisted []string
	var whitelisted []string
	var marked []string

	repsheet := connection.Cmd("KEYS", "*:repsheet:*:*")
	for i := 0; i < len(repsheet.Elems); i++ {
		value, _ := repsheet.Elems[i].Str()
		parts := strings.Split(value, ":")
		repsheetType := parts[len(parts)-1]

		switch repsheetType {
		case "blacklisted":
			blacklisted = append(blacklisted, parts[0])
		case "whitelisted":
			whitelisted = append(whitelisted, parts[0])
		case "marked":
			marked = append(marked, parts[0])
		}
	}

	var list = make(map[string][]string)
	list["blacklisted"] = blacklisted
	list["whitelisted"] = whitelisted
	list["marked"] = marked

	return list
}
开发者ID:repsheet,项目名称:repsheet,代码行数:28,代码来源:repsheet.go


示例8: Put

// Returns a client back to the pool. If the pool is full the client is closed
// instead. If the client is already closed (due to connection failure or
// what-have-you) it should not be put back in the pool. The pool will create
// more connections as needed.
func (p *Pool) Put(conn *redis.Client) {
	select {
	case p.pool <- conn:
	default:
		conn.Close()
	}
}
开发者ID:KushalP,项目名称:radix,代码行数:11,代码来源:pool.go


示例9: storeCacheValues

func storeCacheValues(rascalData []byte, cdnName string, sampleTime int64, cacheGroupMap map[string]string, redisClient *redis.Client) error {
	/* note about the redis data:
	keys are cdnName:deliveryService:cacheGroup:cacheName:statName
	*/

	type CacheStatsJson struct {
		Pp     string `json:"pp"`
		Date   string `json:"date"`
		Caches map[string]map[string][]struct {
			Index uint64 `json:"index"`
			Time  uint64 `json:"time"`
			Value string `json:"value"`
			Span  uint64 `json:"span"`
		} `json:"caches"`
	}

	var jData CacheStatsJson
	err := json.Unmarshal(rascalData, &jData)
	errHndlr(err, ERROR)
	statCount := 0
	statTotals := make(map[string]float64)
	for cacheName, cacheData := range jData.Caches {
		for statName, statData := range cacheData {
			redisKey := cdnName + ":all:" + cacheGroupMap[cacheName] + ":" + cacheName + ":" + statName
			redisKey = strings.Replace(redisKey, ":bandwidth", ":kbps", 1)
			statValue := statData[0].Value
			//fmt.Printf("%s  ->%s\n", redisKey, statValue)
			statCount++
			statFloatValue, err := strconv.ParseFloat(statValue, 64)
			if err != nil {
				statFloatValue = 0.0
			}
			statTotals[cdnName+":all:"+cacheGroupMap[cacheName]+":all:"+statName] += statFloatValue
			statTotals[cdnName+":all:all:all:"+statName] += statFloatValue
			if statName == "maxKbps" {
				r := redisClient.Cmd("zadd", redisKey, sampleTime, statValue) // only care for the last val here.
				errHndlr(r.Err, ERROR)
			} else {
				r := redisClient.Cmd("rpush", redisKey, statValue)
				errHndlr(r.Err, ERROR)
			}
		}
	}
	for totalKey, totalVal := range statTotals {
		totalKey = strings.Replace(totalKey, ":bandwidth", ":kbps", 1)
		if strings.Contains(totalKey, "maxKbps") {
			r := redisClient.Cmd("zadd", totalKey, sampleTime, strconv.FormatFloat(totalVal, 'f', 2, 64))
			errHndlr(r.Err, ERROR)
		} else {
			r := redisClient.Cmd("rpush", totalKey, strconv.FormatFloat(totalVal, 'f', 2, 64))
			errHndlr(r.Err, ERROR)
		}
		statCount++
	}
	r := redisClient.Cmd("rpush", cdnName+":tstamp", sampleTime)
	errHndlr(r.Err, ERROR)
	log.Info("Saved ", statCount, " values for ", cdnName, " @ ", sampleTime)
	return nil
}
开发者ID:gitvod,项目名称:traffic_control,代码行数:59,代码来源:rascal_2_redis.go


示例10: someFunc

func someFunc(c *redis.Client) (err error) {
	reply := c.Cmd("set", "mykey", "myvalue")
	// what is the recommended error
	if reply.Err != nil {
		return reply.Err
	}
	// some code here
	return
}
开发者ID:rif,项目名称:gocmd,代码行数:9,代码来源:radix.go


示例11: FreeClient

func (rp *redisPool) FreeClient(c *redis.Client) {
	select {
	case rp.client_chan <- c:
		// redisClient on free list; nothing more to do.
	default:
		// Free list full, close connection and let it get GC'd
		log.Info("Free list is full - closing redis connection")
		go c.Close()
	}
}
开发者ID:gitvod,项目名称:traffic_control,代码行数:10,代码来源:rascal_2_redis.go


示例12: search

func search(connection *redis.Client, actor string) bool {
	searchString := fmt.Sprintf("%s:*", actor)
	results := connection.Cmd("KEYS", searchString)

	if len(results.Elems) == 1 {
		return true
	} else {
		return false
	}
}
开发者ID:repsheet,项目名称:visualizer,代码行数:10,代码来源:search.go


示例13: Empty

// Removes and calls Close() on all the connections currently in the pool.
// Assuming there are no other connections waiting to be Put back this method
// effectively closes and cleans up the pool.
func (p *Pool) Empty() {
	var conn *redis.Client
	for {
		select {
		case conn = <-p.pool:
			conn.Close()
		default:
			return
		}
	}
}
开发者ID:KushalP,项目名称:radix,代码行数:14,代码来源:pool.go


示例14: putConn

// Puts the connection back in the pool for the given address. Takes in a
// pointer to an error which can be used to decide whether or not to put the
// connection back. It's a pointer because this method is deferable (like
// CarefullyPut)
func (c *Cluster) putConn(addr string, conn *redis.Client, maybeErr *error) {
	c.callCh <- func(c *Cluster) {
		pool := c.pools[addr]
		if pool == nil {
			conn.Close()
			return
		}

		pool.CarefullyPut(conn, maybeErr)
	}
}
开发者ID:qinguoan,项目名称:rambo_golang,代码行数:15,代码来源:cluster.go


示例15: CarefullyPut

// A useful helper method which acts as a wrapper around Put. It will only
// actually Put the conn back if potentialErr is not an error or is a
// redis.CmdError. It would be used like the following:
//
//	func doSomeThings(p *Pool) error {
//		conn, redisErr := p.Get()
//		if redisErr != nil {
//			return redisErr
//		}
//		defer p.CarefullyPut(conn, &redisErr)
//
//		var i int
//		i, redisErr = conn.Cmd("GET", "foo").Int()
//		if redisErr != nil {
//			return redisErr
//		}
//
//		redisErr = conn.Cmd("SET", "foo", i * 3).Err
//		return redisErr
//	}
//
// If we were just using the normal Put we wouldn't be able to defer it because
// we don't want to Put back a connection which is broken. This method takes
// care of doing that check so we can still use the convenient defer
func (p *Pool) CarefullyPut(conn *redis.Client, potentialErr *error) {
	if potentialErr != nil && *potentialErr != nil {
		// We don't care about command errors, they don't indicate anything
		// about the connection integrity
		if _, ok := (*potentialErr).(*redis.CmdError); !ok {
			conn.Close()
			return
		}
	}
	p.Put(conn)
}
开发者ID:qinguoan,项目名称:rambo_golang,代码行数:35,代码来源:pool.go


示例16: GetDomain

func GetDomain(key string, conn *redis.Client) (string, error) {
	reply := conn.Cmd("HGET", "$domainkeys", key)
	if reply.Type == redis.NilReply {
		return "", reply.Err
	}
	domain, err := reply.Str()
	if err != nil {
		return "", err
	} else {
		return domain, nil
	}
}
开发者ID:ateleshev,项目名称:go-autocompeter,代码行数:12,代码来源:authkeys.go


示例17: storeDsValues

/* the ds json looks like:
{
  "deliveryService": {
    "linear-gbr-hls-sbr": {
      "location.us-ma-woburn.kbps": [{
        "index": 520281,
        "time": 1398893383605,
        "value": "0",
        "span": 520024
      }],
      "location.us-de-newcastle.kbps": [{
        "index": 520281,
        "time": 1398893383605,
        "value": "0",
        "span": 517707
      }],
    }
 }
*/
func storeDsValues(rascalData []byte, cdnName string, sampleTime int64, redisClient *redis.Client, dsAggregate map[string]AggregationConfig) error {
	type DsStatsJson struct {
		Pp              string `json:"pp"`
		Date            string `json:"date"`
		DeliveryService map[string]map[string][]struct {
			Index uint64 `json:"index"`
			Time  uint64 `json:"time"`
			Value string `json:"value"`
			Span  uint64 `json:"span"`
		} `json:"deliveryService"`
	}

	var jData DsStatsJson
	err := json.Unmarshal(rascalData, &jData)
	errHndlr(err, ERROR)
	statCount := 0
	statTotals := make(map[string]float64)
	for dsName, dsData := range jData.DeliveryService {
		for dsMetric, dsMetricData := range dsData {
			keyPart := strings.Replace(dsMetric, "location.", "", -1)
			keyPart = strings.Replace(keyPart, ".kbps", ":all:kbps", -1)
			keyPart = strings.Replace(keyPart, ".tps", ":all:tps", -1)
			keyPart = strings.Replace(keyPart, ".status", ":all:status", -1)
			keyPart = strings.Replace(keyPart, "total:all:", "all:all:", -1) // for consistency all everywhere
			redisKey := cdnName + ":" + dsName + ":" + keyPart
			statValue := dsMetricData[0].Value
			//fmt.Printf("%s  ->%s\n", redisKey, statValue)
			statCount++

			aggConfig, exists := dsAggregate[dsMetric]

			if exists {
				statFloatValue, err := strconv.ParseFloat(statValue, 64)

				if err != nil {
					statFloatValue = 0.0
				}

				statTotals[cdnName+":all:all:all:"+aggConfig.RedisKey] += statFloatValue
			}

			r := redisClient.Cmd("rpush", redisKey, statValue)
			errHndlr(r.Err, ERROR)
		}
	}
	for totalKey, totalVal := range statTotals {
		r := redisClient.Cmd("rpush", totalKey, strconv.FormatFloat(totalVal, 'f', 2, 64))
		errHndlr(r.Err, ERROR)
		statCount++
	}
	log.Info("Saved ", statCount, " ds values for ", cdnName, " @ ", sampleTime)
	return nil
}
开发者ID:gitvod,项目名称:traffic_control,代码行数:72,代码来源:rascal_2_redis.go


示例18: addToList

func addToList(connection *redis.Client, list string, actor string, reason string, ttl int) {
	actorString := fmt.Sprintf("%s:repsheet:ip:%sed", actor, list)

	if reason == "" {
		reason = "true"
	}

	if ttl < 0 {
		connection.Cmd("SET", actorString, reason)
	} else {
		connection.Cmd("SETEX", actorString, ttl, reason)
	}
}
开发者ID:repsheet,项目名称:repsheet,代码行数:13,代码来源:repsheet.go


示例19: benchmark

// benchmark benchmarks the given command with the given parameters
// and displays the given test name.
func benchmark(c *redis.Client, testname string, command string, params ...interface{}) {
	fmt.Printf("===== %s =====\n", testname)
	start := time.Now()

	for i := 0; i < *requests; i++ {
		c.Cmd(command, params...)
	}

	duration := time.Now().Sub(start)
	rps := float64(*requests) / duration.Seconds()
	fmt.Println("Requests per second:", rps)
	fmt.Printf("Duration: %v\n\n", duration.Seconds())
}
开发者ID:qinguoan,项目名称:rambo_golang,代码行数:15,代码来源:bench.go


示例20: CarefullyPutMaster

// A useful helper method, analagous to the pool package's CarefullyPut method.
// Since we don't want to Put a connection which is having connectivity
// issues, this can be defered inside a function to make sure we only put back a
// connection when we should. It should be used like the following:
//
//	func doSomeThings(c *Client) error {
//		conn, redisErr := c.GetMaster("bucket0")
//		if redisErr != nil {
//			return redisErr
//		}
//		defer c.CarefullyPutMaster("bucket0", conn, &redisErr)
//
//		var i int
//		i, redisErr = conn.Cmd("GET", "foo").Int()
//		if redisErr != nil {
//			return redisErr
//		}
//
//		redisErr = conn.Cmd("SET", "foo", i * 3).Err
//		return redisErr
//	}
func (c *Client) CarefullyPutMaster(
	name string, client *redis.Client, potentialErr *error,
) {
	if potentialErr != nil && *potentialErr != nil {
		// If the client sent back that it's READONLY then we don't want to keep
		// this connection around. Otherwise, we don't care about command errors
		if cerr, ok := (*potentialErr).(*redis.CmdError); !ok || cerr.Readonly() {
			client.Close()
			return
		}
	}
	c.PutMaster(name, client)
}
开发者ID:qinguoan,项目名称:rambo_golang,代码行数:34,代码来源:sentinel.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang redis.Reply类代码示例发布时间:2022-05-23
下一篇:
Golang redis.DialTimeout函数代码示例发布时间: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