package redis_test import ( "fmt" "strconv" "github.com/vmihailenco/redis/v2" ) func ExampleNewTCPClient() { client := redis.NewTCPClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) defer client.Close() ping := client.Ping() fmt.Println(ping.Err(), ping.Val()) // Output: PONG } func ExampleNewUnixClient() { client := redis.NewUnixClient(&redis.Options{ Addr: "/tmp/redis.sock", }) defer client.Close() ping := client.Ping() fmt.Println(ping.Err(), ping.Val()) // Output: PONG } func ExampleSet() { client := redis.NewTCPClient(&redis.Options{ Addr: ":6379", }) defer client.Close() set := client.Set("foo", "bar") fmt.Println(set.Err(), set.Val()) get := client.Get("foo") fmt.Println(get.Err(), get.Val()) // Output: OK // bar } func ExamplePipeline() { client := redis.NewTCPClient(&redis.Options{ Addr: ":6379", }) defer client.Close() var set *redis.StatusCmd var get *redis.StringCmd cmds, err := client.Pipelined(func(c *redis.Pipeline) { set = c.Set("key1", "hello1") get = c.Get("key2") }) fmt.Println(err, cmds) fmt.Println(set) fmt.Println(get) // Output: (nil) [SET key1 hello1: OK GET key2: (nil)] // SET key1 hello1: OK // GET key2: (nil) } func incr(tx *redis.Multi) ([]redis.Cmder, error) { get := tx.Get("key") if err := get.Err(); err != nil && err != redis.Nil { return nil, err } val, _ := strconv.ParseInt(get.Val(), 10, 64) cmds, err := tx.Exec(func() { tx.Set("key", strconv.FormatInt(val+1, 10)) }) // Transaction failed. Repeat. if err == redis.Nil { return incr(tx) } return cmds, err } func ExampleMulti() { client := redis.NewTCPClient(&redis.Options{ Addr: ":6379", }) defer client.Close() client.Del("key") tx := client.Multi() defer tx.Close() watch := tx.Watch("key") _ = watch.Err() cmds, err := incr(tx) fmt.Println(err, cmds) // Output: [SET key 1: OK] } func ExamplePubSub() { client := redis.NewTCPClient(&redis.Options{ Addr: ":6379", }) defer client.Close() pubsub := client.PubSub() defer pubsub.Close() err := pubsub.Subscribe("mychannel") _ = err msg, err := pubsub.Receive() fmt.Println(msg, err) pub := client.Publish("mychannel", "hello") _ = pub.Err() msg, err = pubsub.Receive() fmt.Println(msg, err) // Output: &{subscribe mychannel 1} // &{mychannel hello} } func Get(client *redis.Client, key string) *redis.StringCmd { cmd := redis.NewStringCmd("GET", key) client.Process(cmd) return cmd } func ExampleCustomCommand() { client := redis.NewTCPClient(&redis.Options{ Addr: ":6379", }) defer client.Close() get := Get(client, "key_does_not_exist") fmt.Println(get.Err(), get.Val()) // Output: (nil) }