go实现redigo的简单操作

golangæä½redis主è¦æ两个åºï¼go-redisåredigoã两èæä½é½æ¯è¾ç®åï¼åºå«ä¸redigoæ´åä¸ä¸ªclientæ§è¡åç§æä½é½æ¯éè¿Doå½æ°å»åçï¼redis-go对å½æ°çå°è£æ´å¥½ï¼ç¸æ¯ä¹ä¸redigoæä½redisæ¾å¾æäºç¹çãä½æ¯å®æ¹æ´æ¨èredigoï¼æ以项ç®ä¸­æ使ç¨äºredigoã

1.è¿æ¥redis

package redisclient
import (
  "fmt"
  redigo "github.com/garyburd/redigo/redis"
)
var pool *redigo.Pool
func init() {
  redis_host := "127.0.0.1"
  redis_port := 6379
  pool_size := 20
  pool = redigo.NewPool(func() (redigo.Conn, error) {
    c, err := redigo.Dial("tcp", fmt.Sprintf("%s:%d", redis_host, redis_port))
    if err != nil {
      return nil, err
    }
    return c, nil
  }, pool_size)
}
func Get() redigo.Conn {
  return pool.Get()
}

ä¹åæ们è°ç¨redisclientå中ç.Get()å°±å¯ä»¥çæä¸ä¸ªredisè¿æ¥æ± å¯¹è±¡æ¥æä½redis

2.æä½redis

package main
import (
  "redisclient"
  "logger"
  "github.com/garyburd/redigo/redis"
)
func main() {
  c := redisclient.Get()
  //è®°å¾éæ¯æ¬æ¬¡é¾è¿æ¥
  defer c.Close()
  //åå¥æ°æ®
  _, err := c.Do("SET", "go_key", "redigo")
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting")
  }
  //å¤æ­keyæ¯å¦å­å¨
  is_key_exit, err := redis.Bool(c.Do("EXISTS", "go_key"))
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while existing")
  }
  //è·åvalue并转æå­ç¬¦ä¸²
  account_balance, err := redis.String(c.Do("GET", "go_key"))
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while getting")
  }
  //å é¤key
  _, err = c.Do("DEL", "go_key")
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while deleting")
  }
  //设置keyè¿ææ¶é´
  _, err = c.Do("SET", "mykey", "superWang", "EX", "5")
  if err != nil {
    fmt.Println("redis set failed:", err)
  }
  //å建keyæ¶è®¾ç½®5sè¿æ
  _, err := c.Do("SET", "go_key:ex", "redigo", "EX", 5)
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting")
  }
  //对已ækey设置5sè¿ææ¶é´
  n, err := rs.Do("EXPIRE", "go_key", 5)
  if err != nil {
    logger.Runtime().Info(map[string]interface{}{"error": err}, "error while setting")
  } else if n != int64(1) {
    fmt.Println("failed")
  }
}

以ä¸å°±æ¯æ¬æçå¨é¨å容ï¼å¸æ对大家ç学习ææ帮å©ï¼ä¹å¸æ大家å¤å¤æ¯æèæ¬ä¹å®¶ã

相关推荐