redis/example_test.go

502 lines
10 KiB
Go
Raw Permalink Normal View History

package redis_test
import (
"errors"
"fmt"
"sync"
2015-05-23 14:15:05 +03:00
"time"
2019-08-08 14:29:44 +03:00
"github.com/go-redis/redis/v7"
)
2019-08-18 17:24:17 +03:00
var rdb *redis.Client
2014-05-11 11:42:40 +04:00
func init() {
2019-08-18 17:24:17 +03:00
rdb = redis.NewClient(&redis.Options{
2016-03-19 17:55:22 +03:00
Addr: ":6379",
DialTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
PoolSize: 10,
PoolTimeout: 30 * time.Second,
})
}
2015-05-02 16:19:22 +03:00
func ExampleNewClient() {
2019-08-18 17:24:17 +03:00
rdb := redis.NewClient(&redis.Options{
2019-01-13 11:36:38 +03:00
Addr: "localhost:6379", // use default Addr
Password: "", // no password set
DB: 0, // use default DB
2014-05-11 11:42:40 +04:00
})
2014-07-13 16:49:33 +04:00
2019-08-18 17:24:17 +03:00
pong, err := rdb.Ping().Result()
2014-07-13 16:49:33 +04:00
fmt.Println(pong, err)
// Output: PONG <nil>
}
2017-06-09 13:55:45 +03:00
func ExampleParseURL() {
opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1")
if err != nil {
panic(err)
}
fmt.Println("addr is", opt.Addr)
fmt.Println("db is", opt.DB)
fmt.Println("password is", opt.Password)
// Create client as usually.
_ = redis.NewClient(opt)
// Output: addr is localhost:6379
// db is 1
// password is qwerty
}
2014-07-13 16:49:33 +04:00
func ExampleNewFailoverClient() {
// See http://redis.io/topics/sentinel for instructions how to
// setup Redis Sentinel.
2019-08-18 17:24:17 +03:00
rdb := redis.NewFailoverClient(&redis.FailoverOptions{
2015-01-25 15:33:30 +03:00
MasterName: "master",
2014-07-13 16:49:33 +04:00
SentinelAddrs: []string{":26379"},
})
2019-08-18 17:24:17 +03:00
rdb.Ping()
}
func ExampleNewClusterClient() {
// See http://redis.io/topics/cluster-tutorial for instructions
// how to setup Redis Cluster.
2019-08-18 17:24:17 +03:00
rdb := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})
2019-08-18 17:24:17 +03:00
rdb.Ping()
}
2018-06-29 10:45:05 +03:00
// Following example creates a cluster from 2 master nodes and 2 slave nodes
// without using cluster mode or Redis Sentinel.
func ExampleNewClusterClient_manualSetup() {
2018-07-18 15:28:51 +03:00
// clusterSlots returns cluster slots information.
// It can use service like ZooKeeper to maintain configuration information
// and Cluster.ReloadState to manually trigger state reloading.
clusterSlots := func() ([]redis.ClusterSlot, error) {
2018-06-29 10:45:05 +03:00
slots := []redis.ClusterSlot{
// First node with 1 master and 1 slave.
{
Start: 0,
End: 8191,
Nodes: []redis.ClusterNode{{
Addr: ":7000", // master
}, {
Addr: ":8000", // 1st slave
}},
},
// Second node with 1 master and 1 slave.
{
Start: 8192,
End: 16383,
Nodes: []redis.ClusterNode{{
Addr: ":7001", // master
}, {
Addr: ":8001", // 1st slave
}},
},
}
return slots, nil
}
2019-08-18 17:24:17 +03:00
rdb := redis.NewClusterClient(&redis.ClusterOptions{
2018-07-18 15:28:51 +03:00
ClusterSlots: clusterSlots,
2018-06-29 10:45:05 +03:00
RouteRandomly: true,
})
2019-08-18 17:24:17 +03:00
rdb.Ping()
2018-06-29 10:45:05 +03:00
2018-07-18 15:28:51 +03:00
// ReloadState reloads cluster state. It calls ClusterSlots func
// to get cluster slots information.
2019-08-18 17:24:17 +03:00
err := rdb.ReloadState()
2018-06-29 10:45:05 +03:00
if err != nil {
panic(err)
}
}
func ExampleNewRing() {
2019-08-18 17:24:17 +03:00
rdb := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"shard1": ":7000",
"shard2": ":7001",
"shard3": ":7002",
},
})
2019-08-18 17:24:17 +03:00
rdb.Ping()
}
2014-05-11 11:42:40 +04:00
func ExampleClient() {
2019-08-18 17:24:17 +03:00
err := rdb.Set("key", "value", 0).Err()
2015-05-23 14:33:33 +03:00
if err != nil {
2014-07-31 16:18:23 +04:00
panic(err)
}
2019-08-18 17:24:17 +03:00
val, err := rdb.Get("key").Result()
2015-05-23 14:33:33 +03:00
if err != nil {
panic(err)
}
fmt.Println("key", val)
2019-08-18 17:24:17 +03:00
val2, err := rdb.Get("missing_key").Result()
2015-05-23 14:33:33 +03:00
if err == redis.Nil {
2018-08-06 13:59:15 +03:00
fmt.Println("missing_key does not exist")
2015-05-23 14:33:33 +03:00
} else if err != nil {
panic(err)
} else {
2018-08-06 13:59:15 +03:00
fmt.Println("missing_key", val2)
2015-05-23 14:33:33 +03:00
}
// Output: key value
2018-08-06 13:59:15 +03:00
// missing_key does not exist
2014-07-31 16:18:23 +04:00
}
func ExampleConn() {
2019-08-18 17:24:17 +03:00
conn := rdb.Conn()
err := conn.ClientSetName("foobar").Err()
if err != nil {
panic(err)
}
// Open other connections.
for i := 0; i < 10; i++ {
2019-08-18 17:24:17 +03:00
go rdb.Ping()
}
s, err := conn.ClientGetName().Result()
if err != nil {
panic(err)
}
fmt.Println(s)
// Output: foobar
}
2015-08-07 17:02:17 +03:00
func ExampleClient_Set() {
// Last argument is expiration. Zero means the key has no
// expiration time.
2019-08-18 17:24:17 +03:00
err := rdb.Set("key", "value", 0).Err()
2015-08-07 17:02:17 +03:00
if err != nil {
panic(err)
}
// key2 will expire in an hour.
2019-08-18 17:24:17 +03:00
err = rdb.Set("key2", "value", time.Hour).Err()
2015-08-07 17:02:17 +03:00
if err != nil {
panic(err)
}
}
2014-07-31 16:18:23 +04:00
func ExampleClient_Incr() {
2019-08-18 17:24:17 +03:00
result, err := rdb.Incr("counter").Result()
2017-08-04 11:51:14 +03:00
if err != nil {
2014-07-31 16:18:23 +04:00
panic(err)
}
2017-08-04 11:51:14 +03:00
fmt.Println(result)
// Output: 1
}
2015-11-24 10:09:53 +03:00
func ExampleClient_BLPop() {
2019-08-18 17:24:17 +03:00
if err := rdb.RPush("queue", "message").Err(); err != nil {
2015-11-24 10:09:53 +03:00
panic(err)
}
2019-08-18 17:24:17 +03:00
// use `rdb.BLPop(0, "queue")` for infinite waiting time
result, err := rdb.BLPop(1*time.Second, "queue").Result()
2015-11-24 10:09:53 +03:00
if err != nil {
panic(err)
}
fmt.Println(result[0], result[1])
// Output: queue message
}
2015-08-19 11:44:46 +03:00
func ExampleClient_Scan() {
2019-08-18 17:24:17 +03:00
rdb.FlushDB()
2015-08-19 11:44:46 +03:00
for i := 0; i < 33; i++ {
2019-08-18 17:24:17 +03:00
err := rdb.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
2015-08-19 11:44:46 +03:00
if err != nil {
panic(err)
}
}
var cursor uint64
2015-08-19 11:44:46 +03:00
var n int
for {
var keys []string
var err error
2019-08-18 17:24:17 +03:00
keys, cursor, err = rdb.Scan(cursor, "key*", 10).Result()
2015-08-19 11:44:46 +03:00
if err != nil {
panic(err)
}
n += len(keys)
if cursor == 0 {
break
}
}
fmt.Printf("found %d keys\n", n)
// Output: found 33 keys
}
2014-05-11 11:42:40 +04:00
func ExampleClient_Pipelined() {
var incr *redis.IntCmd
2019-08-18 17:24:17 +03:00
_, err := rdb.Pipelined(func(pipe redis.Pipeliner) error {
2016-12-22 14:14:34 +03:00
incr = pipe.Incr("pipelined_counter")
pipe.Expire("pipelined_counter", time.Hour)
2014-07-02 18:55:00 +04:00
return nil
})
fmt.Println(incr.Val(), err)
// Output: 1 <nil>
}
2016-12-22 14:14:34 +03:00
func ExampleClient_Pipeline() {
2019-08-18 17:24:17 +03:00
pipe := rdb.Pipeline()
2016-12-22 14:14:34 +03:00
incr := pipe.Incr("pipeline_counter")
pipe.Expire("pipeline_counter", time.Hour)
// Execute
//
// INCR pipeline_counter
// EXPIRE pipeline_counts 3600
//
2019-08-18 17:24:17 +03:00
// using one rdb-server roundtrip.
2016-12-22 14:14:34 +03:00
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
// Output: 1 <nil>
}
func ExampleClient_TxPipelined() {
var incr *redis.IntCmd
2019-08-18 17:24:17 +03:00
_, err := rdb.TxPipelined(func(pipe redis.Pipeliner) error {
2016-12-22 14:14:34 +03:00
incr = pipe.Incr("tx_pipelined_counter")
pipe.Expire("tx_pipelined_counter", time.Hour)
return nil
})
fmt.Println(incr.Val(), err)
// Output: 1 <nil>
}
func ExampleClient_TxPipeline() {
2019-08-18 17:24:17 +03:00
pipe := rdb.TxPipeline()
2016-12-22 14:14:34 +03:00
incr := pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)
// Execute
//
// MULTI
// INCR pipeline_counter
// EXPIRE pipeline_counts 3600
// EXEC
//
2019-08-18 17:24:17 +03:00
// using one rdb-server roundtrip.
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
// Output: 1 <nil>
}
func ExampleClient_Watch() {
const routineCount = 100
2015-11-15 11:23:00 +03:00
// Transactionally increments key using GET and SET commands.
increment := func(key string) error {
txf := func(tx *redis.Tx) error {
// get current value or zero
n, err := tx.Get(key).Int()
2016-05-02 15:54:15 +03:00
if err != nil && err != redis.Nil {
return err
}
// actual opperation (local in optimistic lock)
n++
// runs only if the watched keys remain unchanged
_, err = tx.TxPipelined(func(pipe redis.Pipeliner) error {
// pipe handles the error case
pipe.Set(key, n, 0)
2016-05-02 15:54:15 +03:00
return nil
})
return err
2015-11-15 11:23:00 +03:00
}
for retries := routineCount; retries > 0; retries-- {
2019-08-18 17:24:17 +03:00
err := rdb.Watch(txf, key)
if err != redis.TxFailedErr {
return err
}
// optimistic lock lost
}
return errors.New("increment reached maximum number of retries")
2014-05-11 11:42:40 +04:00
}
var wg sync.WaitGroup
wg.Add(routineCount)
for i := 0; i < routineCount; i++ {
go func() {
defer wg.Done()
if err := increment("counter3"); err != nil {
fmt.Println("increment error:", err)
}
}()
2014-05-11 11:42:40 +04:00
}
wg.Wait()
2019-08-18 17:24:17 +03:00
n, err := rdb.Get("counter3").Int()
fmt.Println("ended with", n, err)
// Output: ended with 100 <nil>
}
func ExamplePubSub() {
2019-08-18 17:24:17 +03:00
pubsub := rdb.Subscribe("mychannel1")
2018-07-24 10:48:14 +03:00
// Wait for confirmation that subscription is created before publishing anything.
_, err := pubsub.Receive()
if err != nil {
panic(err)
}
2018-07-24 09:41:14 +03:00
// Go channel which receives messages.
ch := pubsub.Channel()
2018-07-24 09:41:14 +03:00
// Publish a message.
2019-08-18 17:24:17 +03:00
err = rdb.Publish("mychannel1", "hello").Err()
2015-09-06 13:50:16 +03:00
if err != nil {
panic(err)
}
2018-07-24 14:50:16 +03:00
time.AfterFunc(time.Second, func() {
// When pubsub is closed channel is closed too.
_ = pubsub.Close()
})
// Consume messages.
for msg := range ch {
2018-07-24 14:50:16 +03:00
fmt.Println(msg.Channel, msg.Payload)
}
2018-07-24 09:41:14 +03:00
// Output: mychannel1 hello
2015-09-06 13:50:16 +03:00
}
func ExamplePubSub_Receive() {
2019-08-18 17:24:17 +03:00
pubsub := rdb.Subscribe("mychannel2")
2015-09-06 13:50:16 +03:00
defer pubsub.Close()
2016-03-15 15:45:04 +03:00
for i := 0; i < 2; i++ {
2015-11-22 15:44:38 +03:00
// ReceiveTimeout is a low level API. Use ReceiveMessage instead.
2017-07-01 13:22:39 +03:00
msgi, err := pubsub.ReceiveTimeout(time.Second)
2015-05-23 14:15:05 +03:00
if err != nil {
2016-03-14 17:51:46 +03:00
break
2015-05-23 14:15:05 +03:00
}
2015-05-23 14:15:05 +03:00
switch msg := msgi.(type) {
case *redis.Subscription:
2016-03-14 17:51:46 +03:00
fmt.Println("subscribed to", msg.Channel)
2017-07-01 13:22:39 +03:00
2019-08-18 17:24:17 +03:00
_, err := rdb.Publish("mychannel2", "hello").Result()
2017-07-01 13:22:39 +03:00
if err != nil {
panic(err)
}
2015-05-23 14:15:05 +03:00
case *redis.Message:
2016-03-14 17:51:46 +03:00
fmt.Println("received", msg.Payload, "from", msg.Channel)
2015-05-23 14:15:05 +03:00
default:
2017-07-01 13:22:39 +03:00
panic("unreached")
2015-05-23 14:15:05 +03:00
}
}
2019-08-18 17:24:17 +03:00
// sent message to 1 rdb
2016-03-14 17:51:46 +03:00
// received hello from mychannel2
}
2014-05-11 11:42:40 +04:00
func ExampleScript() {
2015-06-16 10:31:21 +03:00
IncrByXX := redis.NewScript(`
if redis.call("GET", KEYS[1]) ~= false then
return redis.call("INCRBY", KEYS[1], ARGV[1])
end
return false
`)
2019-08-18 17:24:17 +03:00
n, err := IncrByXX.Run(rdb, []string{"xx_counter"}, 2).Result()
2015-06-16 10:31:21 +03:00
fmt.Println(n, err)
2014-05-11 11:42:40 +04:00
2019-08-18 17:24:17 +03:00
err = rdb.Set("xx_counter", "40", 0).Err()
2015-06-16 10:31:21 +03:00
if err != nil {
panic(err)
}
2014-05-11 11:42:40 +04:00
2019-08-18 17:24:17 +03:00
n, err = IncrByXX.Run(rdb, []string{"xx_counter"}, 2).Result()
2015-06-16 10:31:21 +03:00
fmt.Println(n, err)
2014-05-11 11:42:40 +04:00
2015-06-16 10:31:21 +03:00
// Output: <nil> redis: nil
// 42 <nil>
}
2014-05-11 11:42:40 +04:00
func Example_customCommand() {
2019-08-18 17:24:17 +03:00
Get := func(rdb *redis.Client, key string) *redis.StringCmd {
2017-04-15 13:40:20 +03:00
cmd := redis.NewStringCmd("get", key)
2019-08-18 17:24:17 +03:00
rdb.Process(cmd)
2014-05-11 11:42:40 +04:00
return cmd
}
2019-08-18 17:24:17 +03:00
v, err := Get(rdb, "key_does_not_exist").Result()
2014-05-11 11:42:40 +04:00
fmt.Printf("%q %s", v, err)
// Output: "" redis: nil
}
2016-04-13 11:52:47 +03:00
2018-08-12 11:11:01 +03:00
func Example_customCommand2() {
2020-02-14 15:30:07 +03:00
v, err := rdb.Do("get", "key_does_not_exist").Text()
2018-08-12 11:11:01 +03:00
fmt.Printf("%q %s", v, err)
// Output: "" redis: nil
}
2016-04-13 11:52:47 +03:00
func ExampleScanIterator() {
2019-08-18 17:24:17 +03:00
iter := rdb.Scan(0, "", 0).Iterator()
2016-04-13 11:52:47 +03:00
for iter.Next() {
fmt.Println(iter.Val())
}
if err := iter.Err(); err != nil {
panic(err)
}
}
func ExampleScanCmd_Iterator() {
2019-08-18 17:24:17 +03:00
iter := rdb.Scan(0, "", 0).Iterator()
2016-04-13 11:52:47 +03:00
for iter.Next() {
fmt.Println(iter.Val())
}
if err := iter.Err(); err != nil {
panic(err)
}
}
2017-02-17 13:12:06 +03:00
func ExampleNewUniversalClient_simple() {
2019-08-18 17:24:17 +03:00
rdb := redis.NewUniversalClient(&redis.UniversalOptions{
2017-02-17 13:12:06 +03:00
Addrs: []string{":6379"},
})
2019-08-18 17:24:17 +03:00
defer rdb.Close()
2017-02-17 13:12:06 +03:00
2019-08-18 17:24:17 +03:00
rdb.Ping()
2017-02-17 13:12:06 +03:00
}
func ExampleNewUniversalClient_failover() {
2019-08-18 17:24:17 +03:00
rdb := redis.NewUniversalClient(&redis.UniversalOptions{
2017-02-17 13:12:06 +03:00
MasterName: "master",
Addrs: []string{":26379"},
})
2019-08-18 17:24:17 +03:00
defer rdb.Close()
2017-02-17 13:12:06 +03:00
2019-08-18 17:24:17 +03:00
rdb.Ping()
2017-02-17 13:12:06 +03:00
}
func ExampleNewUniversalClient_cluster() {
2019-08-18 17:24:17 +03:00
rdb := redis.NewUniversalClient(&redis.UniversalOptions{
2017-02-17 13:12:06 +03:00
Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})
2019-08-18 17:24:17 +03:00
defer rdb.Close()
2017-02-17 13:12:06 +03:00
2019-08-18 17:24:17 +03:00
rdb.Ping()
2017-02-17 13:12:06 +03:00
}