8.2 Go与各种Redis数据类型

8.2.1 读写列表类对象

工程结构如下:

(base) yanglei@yuanhong redisDataType % tree ./
./
├── conn
│   ├── pool.go
│   └── redis.go
├── dataType
│   └── list
│       └── list.go
├── go.mod
├── go.sum
└── main.go

3 directories, 6 files

其中conn/目录下的文件和上一小节的完全相同.

dataType/list/list.go:

package list

import (
	"github.com/gomodule/redigo/redis"
)

func LPush(conn redis.Conn, key string, values ...string) (int, error) {
	length := 0

	for _, value := range values {
		err := conn.Send("LPUSH", key, value)
		if err != nil {
			return 0, err
		}
	}
	err := conn.Flush()
	if err != nil {
		return 0, err
	}

	for i := 0; i < len(values); i++ {
		reply, _ := redis.Int(conn.Receive())
		length = reply
	}

	return length, nil
}

func RPush(conn redis.Conn, key string, values ...string) (int, error) {
	length := 0

	for _, value := range values {
		err := conn.Send("RPUSH", key, value)
		if err != nil {
			return 0, err
		}
	}
	err := conn.Flush()
	if err != nil {
		return 0, err
	}

	for i := 0; i < len(values); i++ {
		reply, _ := redis.Int(conn.Receive())
		length = reply
	}

	return length, nil
}

func LPop(conn redis.Conn, key string) (string, error) {
	return redis.String(conn.Do("LPOP", key))
}

func RPop(conn redis.Conn, key string) (string, error) {
	return redis.String(conn.Do("RPOP", key))
}

func LLen(conn redis.Conn, key string) (int, error) {
	return redis.Int(conn.Do("LLEN", key))
}

func LRange(conn redis.Conn, key string, start int, end int) ([]string, error) {
	return redis.Strings(conn.Do("LRANGE", key, start, end))
}

func LTrim(conn redis.Conn, key string, start int, end int) (string, error) {
	return redis.String(conn.Do("LTRIM", key, start, end))
}

func LSet(conn redis.Conn, key string, index int, value string) (string, error) {
	return redis.String(conn.Do("LSET", key, index, value))
}

func LIndex(conn redis.Conn, key string, index int) (string, error) {
	return redis.String(conn.Do("LINDEX", key, index))
}

main.go:

运行结果如下:

8.2.2 读写哈希表类对象

工程结构如下:

dataType/hash/hash.go:

main.go:

8.2.3 读写集合类对象

工程结构如下:

dataType/set/set.go:

main.go:

运行结果如下:

8.2.4 读写有序集合类对象

工程结构如下:

dataType/sortedSet/sortedSet.go:

main.go:

运行结果:

8.2.5 操作地理位置数据

Last updated