Go core development study notes (thirty-one) - Golang operating Redis

Redis installation and rationale please refer to the relevant information to learn.

Redis basics and developed using:

1.0 - 16 15 Total library.
2. Typical KV storage.
3. Common Operation Commands:
(1) adding kV: SET
(2) Find all key: keys <pattern regular>
(3) to find the corresponding key value: GET
(. 4) switching database: SELECT <0-15 NUM>
(. 5 ) number of key-value See: dbsize (no parameters for the current library)
(6) empty database: flushdb (current library); flushall (all banks)
4. five data types: String, hash (dictionary-like, a plurality of pairs kv) , list, set, zset (ordered set):

  • (1) String:
    Redis most basic type, kv on;
    binary storage, in addition to the string can put pictures and other data, the program read out without problems, binary save Chinese.
    512MB maximum string value;
    setex(set with expire): setex <keyname> <n seconds> <value> //多少秒过后,这个value就被销毁了; mset(多个kv对设置): mset <k1> <v1> <k2> <k2> //如何获得: mget <k1> <k2>。

  • (2) Hash:
    key to the collection, Similar dictionary, var golang map [string] string ;
    particularly suited for storing objects, that is, in the structure golang;
    hset cxk hobby sing ; hset cxk name caixukun // hget cxk name 就能取到name对应的value。 hmset cxk name caixk age 20 song "鸡你太美" // hmget cxk name age song 一次取到设置并取多个字段的values。 hlen cxk //查看Hash元素有多少个。 hexists cxk song //查看cxk这个hash中是否有song这个字段。

  • (3) List:
    a simple list of strings, sort order in accordance with the insertion, an element may be added to the head or tail of the list;
    List is essentially a list, List elements are ordered ([n] List), the value of the element It can be repeated;
    note lpop / rpop usage is very common; lpush similar push, rpush similar queue.

  • (4) Set (Zset Similarly):
    the Set unordered collection of type string;
    underlying data structure is Hashtable, hold a lot of string elements, unordered string element, and the element values can not be repeated, for example, an employee ID storage number, email, phone number, QQ number and so the only non-duplicate content;
    sadd emails [email protected] [email protected] //创建并添加集合的k名和v的内容; smembers emails //遍历所有集合中的内容; sismenber emails damn //检查集合中是否存在damn,有返回1,没有就返回0; srem emails [email protected] //删除集合中指定值;

The data type and the CRUD:
(. 1) String:
the CU: SET <KeyName> <ValueName> // the SET key is not created, there would modify
D: del <KeyName>
R & lt: GET <KeyName>
(2) the Hash:
the CU: HSET <hashname> <KeyName> <ValueName>
R & lt: hget <hashname> <KeyName>; hgetall
D: HDEL <hashname>
(. 3) List:
the CU: LPUSH / RPUSH <listname> ... // VALUE1 left right value2 value3 data are inserted
lpop / rpop <listname> // taken left / right take each element
R: lrange <listname> [number] [Last number] // begin to show only the left side from the starting to the end 0 -1 segment of data
lindex <listname> <index> // get the list by the index value in the corresponding element
llen <listname> // Check the number of elements
D: del <listname>
(. 4) the Set:
the CU: Sadd <KeyName> < value1> <value2>
R: smembers <keyname> // through all values;
sismember <keyname> <dest-value > // if there are x, a presence, absence 0;
D: Srem <KeyName> <dest-value> // return a successful delete unsuccessful return 0;

How redis by Golang

  1. To ensure that the system is installed git .
  2. Switch to GOPATH directory: "Go GET github.com \ garyburd \ redigo \ redis" can download related redis the src packet to the next, thereby Import redis packages, and methods of use related properties.

Case 1: Golang redis operation, a string to string instructions, data type of the remaining parameters passed redis exactly the same command line:

package main

import (
	"fmt"
"github.com/garyburd/redigo/redis"
)

func main() {
	//连接数据库
	conn, err := redis.Dial("tcp","127.0.0.1:6379")
	if err != nil {
		fmt.Println("连接失败,错误为:",err)
		return
	}
	defer conn.Close()

	//添加一对键值对,我们所需要的仅仅是添加结果成功就可以,无需返回值
	_, err = conn.Do("set", "email", "damn")      //conn.Do()用的是最多的,把命令行中的args一个个写进去
	if err != nil {
		fmt.Println("设置kv失败,错误原因为:",err)
		return
	}

	_, err = conn.Do("setex", "email1", 10,"shit")      //conn.Do()用的是最多的,把命令行中的args一个个写进去
	if err != nil {
		fmt.Println("设置kv失败,错误原因为:",err)
		return
	}

	//取得一个键对应的一个值,判断获取的值得类型为xx
	//get返回时空接口类型,使用断言报错,直接使用redis提供的转换方法即可
	res, err := redis.String(conn.Do("get","email"))
	if err != nil {
		fmt.Println("获取key失败,错误原因为:",err)
		return
	}
	fmt.Println(res)
}

Case 2: Golang operation redis, use the hash of the string

package main

import (
	"fmt"
"github.com/garyburd/redigo/redis"
)

func main() {
	//连接数据库
	conn, err := redis.Dial("tcp","127.0.0.1:6379")
	if err != nil {
		fmt.Println("连接失败,错误为:",err)
		return
	}
	defer conn.Close()

	//添加一个hash
	_, err = conn.Do("hmset", "hhash", "name","damn","age",27)
	if err != nil {
		fmt.Println("设置kv失败,错误原因为:",err)
		return
	}
	//取得一个键对应的一个值,判断获取的值得类型为xx
	//get返回时空接口类型,使用断言报错,直接使用redis提供的转换方法即可
	res, err := redis.Strings(conn.Do("hmget","hhash","name","age"))  //注意这里变为Strings
	if err != nil {
		fmt.Println("获取key失败,错误原因为:",err)
		return
	}
	for i, v := range res {  //res应该是集合类数据,在golang中也应该是数组切片之类的。
		fmt.Println(v)      //遍历的方式,也可以带上索引或者不带
	}
}

Redis connection pool

  1. Link initialization achieve a certain number of links into the pool;
  2. Go when action is required redis, taken directly from link to link cell;
  3. This saves the temporary link redis get time to improve efficiency.

Case: init () was founded redis connection pooling, resource links directly to obtain the code behind the link from the pool and read and write

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)

var pool *redis.Pool
/*
	type Pool struct {
		Dial func() (Conn, error)
		// Maximum number of idle connections in the pool.
		MaxIdle 8       //最大空闲数为8
		MaxActive 0      //0表示无限制链接,支持最高并发数
		IdleTimeout 100 //time.Duration
	}
*/

func init() {      //初始化函数,执行main之前优先创建链接池,链接池的意义在于迅速响应go链接,不用从头开始建立tcp链接

	pool =  &redis.Pool{

		Dial: func() (redis.Conn, error){
			return redis.Dial("tcp","127.0.0.1:6379")
			},
		MaxIdle: 8,       //最大空闲数为8
		MaxActive: 0,      //0表示无限制链接,支持最高并发数
		IdleTimeout: 100, //time.Duration
		}
}

func main() {
	//从创建好的链接池中取出一个链接
	/*
	func (p *Pool) Get() Conn {
		pc, err := p.get(nil)
		if err != nil {
			return errorConn{err}
		}
		return &activeConn{p: p, pc: pc}
	}
	 */
	conn := pool.Get()   //从redis链接池中取出一个链接,和之前redis.Dial是一个意思
	defer conn.Close()   //开销类资源一定要使用defer关闭,如果要取值一定要保证链接池开启,关闭后 get on closed pool报错

	//链接redis,创建添加一个kv,并查询kv
	_, err := conn.Do("Set","cxk","鸡你太美")
	if err != nil {
		fmt.Println("SET 添加字段有误,错误为:",err)
		return
	}

	ret, err1 := redis.String(conn.Do("Get","cxk"))
	if err1 != nil {
		fmt.Println("GET 读取字段有误,错误为:",err1)
		return
	}
	fmt.Println("Get 取值为:",ret)    //Get 取值为: 鸡你太美
}
Published 49 original articles · won praise 18 · views 3994

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/90701111