Redis [8]

各种语言使用 Redis

Posted by ZYT on November 17, 2018

Python

安装依赖

首先需要安装依赖包 redis-py

$ pip install redis

Getting Started

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'

默认情况下,所有响应在 Python3 是 bytes 类型,在 Python2 是 str 类型。如果所有从客户端返回的数据需要进行解码,可以指定 decode_responses=True

redis 的分布式锁 介绍的单节点分布式锁,可以方便的实现:

try:
    with r.lock('my-lock-key', blocking_timeout=5) as lock:
        # code you want executed only after the lock has been acquired
except LockError:
    # the lock wasn't acquired

具体的信息可以查看 redis-py 的文档

Go

安装依赖

首先需要安装依赖包 go-redis

$ go get -u github.com/go-redis/redis

Getting Started

demo:

import (
	"fmt"
	"github.com/go-redis/redis"
)

func main() {
	// connect redis
	client := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
		Password: "",
		DB: 0,
	})
    defer client.Close()

	pong, connectErr := client.Ping().Result()
	fmt.Println(pong, connectErr)
	// Output: PONG <nil>

	// set value
	setErr := client.Set("key", "value", 0).Err()
	if setErr != nil {
		panic(setErr)
	}

	// get value
	val, getErr := client.Get("key").Result()
	if getErr != nil {
		panic(getErr)
	}
	fmt.Println("key: ", val)
	// Output: key:  value
}

同样也可以快速实现分布式锁(需要安装 github.com/bsm/redis-lock):

import (
  "fmt"
  "time"

  "github.com/bsm/redis-lock"
  "github.com/go-redis/redis"
)

func main() {
	// Connect to Redis
	client := redis.NewClient(&redis.Options{
		Network:	"tcp",
		Addr:		"127.0.0.1:6379",
	})
	defer client.Close()

	// Obtain a new lock with default settings
	lock, err := lock.Obtain(client, "lock.foo", nil)
	if err != nil {
		fmt.Printf("ERROR: %s\n", err.Error())
		return
	} else if lock == nil {
		fmt.Println("ERROR: could not obtain lock")
		return
	}

	// Don't forget to unlock in the end
	defer lock.Unlock()

	// Run something
	fmt.Println("I have a lock!")
	time.Sleep(200 * time.Millisecond)

	// Renew your lock
	ok, err := lock.Lock()
	if err != nil {
		fmt.Printf("ERROR: %s\n", err.Error())
		return
	} else if !ok {
		fmt.Println("ERROR: could not renew lock")
		return
	}
	fmt.Println("I have renewed my lock!")

}

具体的 go-redis 信息可以查看 go-redis 的文档

具体的 redis-lock 信息可以查看 redis-lock 的文档