• [go]redis基本使用


    redis 数据结构操作

    import (
    	"github.com/garyburd/redigo/redis"
    )       
    
    
    // set
    c, err := redis.Dial("tcp", "localhost:16379")
    _, err = c.Do("Set", "abc", 100)
    r, err := redis.Int(c.Do("Get", "abc"))
    
    //mset
    _, err = c.Do("MSet", "abc", 100, "efg", 300)
    r, err := redis.Ints(c.Do("MGet", "abc", "efg"))
    
    
    
    //list
    _, err = c.Do("lpush", "book_list", "abc", "ceg", 300)
    r, err := redis.String(c.Do("rpop", "book_list"))
    
    //hash字典
    _, err = c.Do("HSet", "books", "abc", 100)
    r, err := redis.Int(c.Do("HGet", "books", "abc"))
    
    
    //超时
    _, err = c.Do("expire", "abc", 10)
    

    redis连接池

    package main
    
    import (
    	"fmt"
    
    	"github.com/garyburd/redigo/redis"
    	"time"
    )
    
    var pool *redis.Pool
    
    //初始化一个pool
    func newPool(server, password string) *redis.Pool {
    	return &redis.Pool{
    		MaxIdle:     64,
    		MaxActive:   1000,
    		IdleTimeout: 240 * time.Second,
    		Dial: func() (redis.Conn, error) {
    			c, err := redis.Dial("tcp", server)
    			if err != nil {
    				return nil, err
    			}
    			/*
    			   if _, err := c.Do("AUTH", password); err != nil {
    			   c.Close()
    			   return nil, err
    			   }*/
    			return c, err
    		},
    		TestOnBorrow: func(c redis.Conn, t time.Time) error {
    			if time.Since(t) < time.Minute {
    				return nil
    			}
    			_, err := c.Do("PING")
    			return err
    		},
    	}
    }
    
    func main() {
    	pool = newPool("localhost:16379", "")
    	for {
    		time.Sleep(time.Second)
    		conn := pool.Get()
    		conn.Do("set", "abc", 100)
    
    		r, err := redis.Int(conn.Do("get", "abc"))
    		if err != nil {
    			fmt.Printf("do failed, err:%v
    ", err)
    			continue
    		}
    
    		fmt.Printf("get from redis, result:%v
    ", r)
    	}
    
    	/*
    		c, err := redis.Dial("tcp", "localhost:16379")
    		if err != nil {
    			fmt.Println("conn redis failed,", err)
    			return
    		}
    		defer c.Close()
    		_, err = c.Do("Set", "abc", 100)
    		if err != nil {
    			fmt.Println(err)
    			return
    		}
    		r, err := redis.Int(c.Do("Get", "abc"))
    		if err != nil {
    			fmt.Println("get abc failed,", err)
    			return
    		}
    		fmt.Println("get from redis", r)
    	*/
    }
    
    
  • 相关阅读:
    Hbase王国游记之:Hbase客户端API初体验
    Hbase给初学者的“下马威”
    五分钟轻松了解Hbase面向列的存储
    JsonBuilder初出茅庐
    如何查看laravel门脸类包含方法的源码
    PHP常用数组函数
    Go语言strings包
    PHP获取远程http或ftp文件的md5值
    Git使用详细教程(9):git log
    PHP Iterator迭代对象属性
  • 原文地址:https://www.cnblogs.com/iiiiiher/p/11955088.html
Copyright © 2020-2023  润新知