zoukankan      html  css  js  c++  java
  • [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)
    	*/
    }
    
    
  • 相关阅读:
    Spring MVC笔记(二) Hello World实例
    Spring MVC笔记(一) Spring MVC概述
    正则表达式在python中的应用
    Spring与Ibatis整合入门
    Spark GraphX的函数源码分析及应用实例
    Python爬虫获取迅雷会员帐号
    Linux Shell编程学习笔记
    Hadoop在linux下无法启动DataNode解决方法
    Ubuntu中使用终端运行Hadoop程序
    Hadoop2.6.0在Ubuntu Kylin14.04上的配置
  • 原文地址:https://www.cnblogs.com/iiiiiher/p/11955088.html
Copyright © 2011-2022 走看看