...

Source file src/github.com/go-redis/redis/example_test.go

Documentation: github.com/go-redis/redis

     1  package redis_test
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"sync"
     7  	"time"
     8  
     9  	"github.com/go-redis/redis"
    10  )
    11  
    12  var redisdb *redis.Client
    13  
    14  func init() {
    15  	redisdb = redis.NewClient(&redis.Options{
    16  		Addr:         ":6379",
    17  		DialTimeout:  10 * time.Second,
    18  		ReadTimeout:  30 * time.Second,
    19  		WriteTimeout: 30 * time.Second,
    20  		PoolSize:     10,
    21  		PoolTimeout:  30 * time.Second,
    22  	})
    23  }
    24  
    25  func ExampleNewClient() {
    26  	redisdb := redis.NewClient(&redis.Options{
    27  		Addr:     "localhost:6379", // use default Addr
    28  		Password: "",               // no password set
    29  		DB:       0,                // use default DB
    30  	})
    31  
    32  	pong, err := redisdb.Ping().Result()
    33  	fmt.Println(pong, err)
    34  	// Output: PONG <nil>
    35  }
    36  
    37  func ExampleParseURL() {
    38  	opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1")
    39  	if err != nil {
    40  		panic(err)
    41  	}
    42  	fmt.Println("addr is", opt.Addr)
    43  	fmt.Println("db is", opt.DB)
    44  	fmt.Println("password is", opt.Password)
    45  
    46  	// Create client as usually.
    47  	_ = redis.NewClient(opt)
    48  
    49  	// Output: addr is localhost:6379
    50  	// db is 1
    51  	// password is qwerty
    52  }
    53  
    54  func ExampleNewFailoverClient() {
    55  	// See http://redis.io/topics/sentinel for instructions how to
    56  	// setup Redis Sentinel.
    57  	redisdb := redis.NewFailoverClient(&redis.FailoverOptions{
    58  		MasterName:    "master",
    59  		SentinelAddrs: []string{":26379"},
    60  	})
    61  	redisdb.Ping()
    62  }
    63  
    64  func ExampleNewClusterClient() {
    65  	// See http://redis.io/topics/cluster-tutorial for instructions
    66  	// how to setup Redis Cluster.
    67  	redisdb := redis.NewClusterClient(&redis.ClusterOptions{
    68  		Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
    69  	})
    70  	redisdb.Ping()
    71  }
    72  
    73  // Following example creates a cluster from 2 master nodes and 2 slave nodes
    74  // without using cluster mode or Redis Sentinel.
    75  func ExampleNewClusterClient_manualSetup() {
    76  	// clusterSlots returns cluster slots information.
    77  	// It can use service like ZooKeeper to maintain configuration information
    78  	// and Cluster.ReloadState to manually trigger state reloading.
    79  	clusterSlots := func() ([]redis.ClusterSlot, error) {
    80  		slots := []redis.ClusterSlot{
    81  			// First node with 1 master and 1 slave.
    82  			{
    83  				Start: 0,
    84  				End:   8191,
    85  				Nodes: []redis.ClusterNode{{
    86  					Addr: ":7000", // master
    87  				}, {
    88  					Addr: ":8000", // 1st slave
    89  				}},
    90  			},
    91  			// Second node with 1 master and 1 slave.
    92  			{
    93  				Start: 8192,
    94  				End:   16383,
    95  				Nodes: []redis.ClusterNode{{
    96  					Addr: ":7001", // master
    97  				}, {
    98  					Addr: ":8001", // 1st slave
    99  				}},
   100  			},
   101  		}
   102  		return slots, nil
   103  	}
   104  
   105  	redisdb := redis.NewClusterClient(&redis.ClusterOptions{
   106  		ClusterSlots:  clusterSlots,
   107  		RouteRandomly: true,
   108  	})
   109  	redisdb.Ping()
   110  
   111  	// ReloadState reloads cluster state. It calls ClusterSlots func
   112  	// to get cluster slots information.
   113  	err := redisdb.ReloadState()
   114  	if err != nil {
   115  		panic(err)
   116  	}
   117  }
   118  
   119  func ExampleNewRing() {
   120  	redisdb := redis.NewRing(&redis.RingOptions{
   121  		Addrs: map[string]string{
   122  			"shard1": ":7000",
   123  			"shard2": ":7001",
   124  			"shard3": ":7002",
   125  		},
   126  	})
   127  	redisdb.Ping()
   128  }
   129  
   130  func ExampleClient() {
   131  	err := redisdb.Set("key", "value", 0).Err()
   132  	if err != nil {
   133  		panic(err)
   134  	}
   135  
   136  	val, err := redisdb.Get("key").Result()
   137  	if err != nil {
   138  		panic(err)
   139  	}
   140  	fmt.Println("key", val)
   141  
   142  	val2, err := redisdb.Get("missing_key").Result()
   143  	if err == redis.Nil {
   144  		fmt.Println("missing_key does not exist")
   145  	} else if err != nil {
   146  		panic(err)
   147  	} else {
   148  		fmt.Println("missing_key", val2)
   149  	}
   150  	// Output: key value
   151  	// missing_key does not exist
   152  }
   153  
   154  func ExampleClient_Set() {
   155  	// Last argument is expiration. Zero means the key has no
   156  	// expiration time.
   157  	err := redisdb.Set("key", "value", 0).Err()
   158  	if err != nil {
   159  		panic(err)
   160  	}
   161  
   162  	// key2 will expire in an hour.
   163  	err = redisdb.Set("key2", "value", time.Hour).Err()
   164  	if err != nil {
   165  		panic(err)
   166  	}
   167  }
   168  
   169  func ExampleClient_Incr() {
   170  	result, err := redisdb.Incr("counter").Result()
   171  	if err != nil {
   172  		panic(err)
   173  	}
   174  
   175  	fmt.Println(result)
   176  	// Output: 1
   177  }
   178  
   179  func ExampleClient_BLPop() {
   180  	if err := redisdb.RPush("queue", "message").Err(); err != nil {
   181  		panic(err)
   182  	}
   183  
   184  	// use `redisdb.BLPop(0, "queue")` for infinite waiting time
   185  	result, err := redisdb.BLPop(1*time.Second, "queue").Result()
   186  	if err != nil {
   187  		panic(err)
   188  	}
   189  
   190  	fmt.Println(result[0], result[1])
   191  	// Output: queue message
   192  }
   193  
   194  func ExampleClient_Scan() {
   195  	redisdb.FlushDB()
   196  	for i := 0; i < 33; i++ {
   197  		err := redisdb.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
   198  		if err != nil {
   199  			panic(err)
   200  		}
   201  	}
   202  
   203  	var cursor uint64
   204  	var n int
   205  	for {
   206  		var keys []string
   207  		var err error
   208  		keys, cursor, err = redisdb.Scan(cursor, "key*", 10).Result()
   209  		if err != nil {
   210  			panic(err)
   211  		}
   212  		n += len(keys)
   213  		if cursor == 0 {
   214  			break
   215  		}
   216  	}
   217  
   218  	fmt.Printf("found %d keys\n", n)
   219  	// Output: found 33 keys
   220  }
   221  
   222  func ExampleClient_Pipelined() {
   223  	var incr *redis.IntCmd
   224  	_, err := redisdb.Pipelined(func(pipe redis.Pipeliner) error {
   225  		incr = pipe.Incr("pipelined_counter")
   226  		pipe.Expire("pipelined_counter", time.Hour)
   227  		return nil
   228  	})
   229  	fmt.Println(incr.Val(), err)
   230  	// Output: 1 <nil>
   231  }
   232  
   233  func ExampleClient_Pipeline() {
   234  	pipe := redisdb.Pipeline()
   235  
   236  	incr := pipe.Incr("pipeline_counter")
   237  	pipe.Expire("pipeline_counter", time.Hour)
   238  
   239  	// Execute
   240  	//
   241  	//     INCR pipeline_counter
   242  	//     EXPIRE pipeline_counts 3600
   243  	//
   244  	// using one redisdb-server roundtrip.
   245  	_, err := pipe.Exec()
   246  	fmt.Println(incr.Val(), err)
   247  	// Output: 1 <nil>
   248  }
   249  
   250  func ExampleClient_TxPipelined() {
   251  	var incr *redis.IntCmd
   252  	_, err := redisdb.TxPipelined(func(pipe redis.Pipeliner) error {
   253  		incr = pipe.Incr("tx_pipelined_counter")
   254  		pipe.Expire("tx_pipelined_counter", time.Hour)
   255  		return nil
   256  	})
   257  	fmt.Println(incr.Val(), err)
   258  	// Output: 1 <nil>
   259  }
   260  
   261  func ExampleClient_TxPipeline() {
   262  	pipe := redisdb.TxPipeline()
   263  
   264  	incr := pipe.Incr("tx_pipeline_counter")
   265  	pipe.Expire("tx_pipeline_counter", time.Hour)
   266  
   267  	// Execute
   268  	//
   269  	//     MULTI
   270  	//     INCR pipeline_counter
   271  	//     EXPIRE pipeline_counts 3600
   272  	//     EXEC
   273  	//
   274  	// using one redisdb-server roundtrip.
   275  	_, err := pipe.Exec()
   276  	fmt.Println(incr.Val(), err)
   277  	// Output: 1 <nil>
   278  }
   279  
   280  func ExampleClient_Watch() {
   281  	const routineCount = 100
   282  
   283  	// Transactionally increments key using GET and SET commands.
   284  	increment := func(key string) error {
   285  		txf := func(tx *redis.Tx) error {
   286  			// get current value or zero
   287  			n, err := tx.Get(key).Int()
   288  			if err != nil && err != redis.Nil {
   289  				return err
   290  			}
   291  
   292  			// actual opperation (local in optimistic lock)
   293  			n++
   294  
   295  			// runs only if the watched keys remain unchanged
   296  			_, err = tx.Pipelined(func(pipe redis.Pipeliner) error {
   297  				// pipe handles the error case
   298  				pipe.Set(key, n, 0)
   299  				return nil
   300  			})
   301  			return err
   302  		}
   303  
   304  		for retries := routineCount; retries > 0; retries-- {
   305  			err := redisdb.Watch(txf, key)
   306  			if err != redis.TxFailedErr {
   307  				return err
   308  			}
   309  			// optimistic lock lost
   310  		}
   311  		return errors.New("increment reached maximum number of retries")
   312  	}
   313  
   314  	var wg sync.WaitGroup
   315  	wg.Add(routineCount)
   316  	for i := 0; i < routineCount; i++ {
   317  		go func() {
   318  			defer wg.Done()
   319  
   320  			if err := increment("counter3"); err != nil {
   321  				fmt.Println("increment error:", err)
   322  			}
   323  		}()
   324  	}
   325  	wg.Wait()
   326  
   327  	n, err := redisdb.Get("counter3").Int()
   328  	fmt.Println("ended with", n, err)
   329  	// Output: ended with 100 <nil>
   330  }
   331  
   332  func ExamplePubSub() {
   333  	pubsub := redisdb.Subscribe("mychannel1")
   334  
   335  	// Wait for confirmation that subscription is created before publishing anything.
   336  	_, err := pubsub.Receive()
   337  	if err != nil {
   338  		panic(err)
   339  	}
   340  
   341  	// Go channel which receives messages.
   342  	ch := pubsub.Channel()
   343  
   344  	// Publish a message.
   345  	err = redisdb.Publish("mychannel1", "hello").Err()
   346  	if err != nil {
   347  		panic(err)
   348  	}
   349  
   350  	time.AfterFunc(time.Second, func() {
   351  		// When pubsub is closed channel is closed too.
   352  		_ = pubsub.Close()
   353  	})
   354  
   355  	// Consume messages.
   356  	for msg := range ch {
   357  		fmt.Println(msg.Channel, msg.Payload)
   358  	}
   359  
   360  	// Output: mychannel1 hello
   361  }
   362  
   363  func ExamplePubSub_Receive() {
   364  	pubsub := redisdb.Subscribe("mychannel2")
   365  	defer pubsub.Close()
   366  
   367  	for i := 0; i < 2; i++ {
   368  		// ReceiveTimeout is a low level API. Use ReceiveMessage instead.
   369  		msgi, err := pubsub.ReceiveTimeout(time.Second)
   370  		if err != nil {
   371  			break
   372  		}
   373  
   374  		switch msg := msgi.(type) {
   375  		case *redis.Subscription:
   376  			fmt.Println("subscribed to", msg.Channel)
   377  
   378  			_, err := redisdb.Publish("mychannel2", "hello").Result()
   379  			if err != nil {
   380  				panic(err)
   381  			}
   382  		case *redis.Message:
   383  			fmt.Println("received", msg.Payload, "from", msg.Channel)
   384  		default:
   385  			panic("unreached")
   386  		}
   387  	}
   388  
   389  	// sent message to 1 redisdb
   390  	// received hello from mychannel2
   391  }
   392  
   393  func ExampleScript() {
   394  	IncrByXX := redis.NewScript(`
   395  		if redis.call("GET", KEYS[1]) ~= false then
   396  			return redis.call("INCRBY", KEYS[1], ARGV[1])
   397  		end
   398  		return false
   399  	`)
   400  
   401  	n, err := IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
   402  	fmt.Println(n, err)
   403  
   404  	err = redisdb.Set("xx_counter", "40", 0).Err()
   405  	if err != nil {
   406  		panic(err)
   407  	}
   408  
   409  	n, err = IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
   410  	fmt.Println(n, err)
   411  
   412  	// Output: <nil> redis: nil
   413  	// 42 <nil>
   414  }
   415  
   416  func Example_customCommand() {
   417  	Get := func(redisdb *redis.Client, key string) *redis.StringCmd {
   418  		cmd := redis.NewStringCmd("get", key)
   419  		redisdb.Process(cmd)
   420  		return cmd
   421  	}
   422  
   423  	v, err := Get(redisdb, "key_does_not_exist").Result()
   424  	fmt.Printf("%q %s", v, err)
   425  	// Output: "" redis: nil
   426  }
   427  
   428  func Example_customCommand2() {
   429  	v, err := redisdb.Do("get", "key_does_not_exist").String()
   430  	fmt.Printf("%q %s", v, err)
   431  	// Output: "" redis: nil
   432  }
   433  
   434  func ExampleScanIterator() {
   435  	iter := redisdb.Scan(0, "", 0).Iterator()
   436  	for iter.Next() {
   437  		fmt.Println(iter.Val())
   438  	}
   439  	if err := iter.Err(); err != nil {
   440  		panic(err)
   441  	}
   442  }
   443  
   444  func ExampleScanCmd_Iterator() {
   445  	iter := redisdb.Scan(0, "", 0).Iterator()
   446  	for iter.Next() {
   447  		fmt.Println(iter.Val())
   448  	}
   449  	if err := iter.Err(); err != nil {
   450  		panic(err)
   451  	}
   452  }
   453  
   454  func ExampleNewUniversalClient_simple() {
   455  	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
   456  		Addrs: []string{":6379"},
   457  	})
   458  	defer redisdb.Close()
   459  
   460  	redisdb.Ping()
   461  }
   462  
   463  func ExampleNewUniversalClient_failover() {
   464  	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
   465  		MasterName: "master",
   466  		Addrs:      []string{":26379"},
   467  	})
   468  	defer redisdb.Close()
   469  
   470  	redisdb.Ping()
   471  }
   472  
   473  func ExampleNewUniversalClient_cluster() {
   474  	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
   475  		Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
   476  	})
   477  	defer redisdb.Close()
   478  
   479  	redisdb.Ping()
   480  }
   481  

View as plain text