example_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package redis_test
  2. import (
  3. "fmt"
  4. "strconv"
  5. "sync"
  6. "time"
  7. "gopkg.in/redis.v5"
  8. )
  9. var client *redis.Client
  10. func init() {
  11. client = redis.NewClient(&redis.Options{
  12. Addr: ":6379",
  13. DialTimeout: 10 * time.Second,
  14. ReadTimeout: 30 * time.Second,
  15. WriteTimeout: 30 * time.Second,
  16. PoolSize: 10,
  17. PoolTimeout: 30 * time.Second,
  18. })
  19. client.FlushDb()
  20. }
  21. func ExampleNewClient() {
  22. client := redis.NewClient(&redis.Options{
  23. Addr: "localhost:6379",
  24. Password: "", // no password set
  25. DB: 0, // use default DB
  26. })
  27. pong, err := client.Ping().Result()
  28. fmt.Println(pong, err)
  29. // Output: PONG <nil>
  30. }
  31. func ExampleNewFailoverClient() {
  32. // See http://redis.io/topics/sentinel for instructions how to
  33. // setup Redis Sentinel.
  34. client := redis.NewFailoverClient(&redis.FailoverOptions{
  35. MasterName: "master",
  36. SentinelAddrs: []string{":26379"},
  37. })
  38. client.Ping()
  39. }
  40. func ExampleNewClusterClient() {
  41. // See http://redis.io/topics/cluster-tutorial for instructions
  42. // how to setup Redis Cluster.
  43. client := redis.NewClusterClient(&redis.ClusterOptions{
  44. Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
  45. })
  46. client.Ping()
  47. }
  48. func ExampleNewRing() {
  49. client := redis.NewRing(&redis.RingOptions{
  50. Addrs: map[string]string{
  51. "shard1": ":7000",
  52. "shard2": ":7001",
  53. "shard3": ":7002",
  54. },
  55. })
  56. client.Ping()
  57. }
  58. func ExampleClient() {
  59. err := client.Set("key", "value", 0).Err()
  60. if err != nil {
  61. panic(err)
  62. }
  63. val, err := client.Get("key").Result()
  64. if err != nil {
  65. panic(err)
  66. }
  67. fmt.Println("key", val)
  68. val2, err := client.Get("key2").Result()
  69. if err == redis.Nil {
  70. fmt.Println("key2 does not exists")
  71. } else if err != nil {
  72. panic(err)
  73. } else {
  74. fmt.Println("key2", val2)
  75. }
  76. // Output: key value
  77. // key2 does not exists
  78. }
  79. func ExampleClient_Set() {
  80. // Last argument is expiration. Zero means the key has no
  81. // expiration time.
  82. err := client.Set("key", "value", 0).Err()
  83. if err != nil {
  84. panic(err)
  85. }
  86. // key2 will expire in an hour.
  87. err = client.Set("key2", "value", time.Hour).Err()
  88. if err != nil {
  89. panic(err)
  90. }
  91. }
  92. func ExampleClient_Incr() {
  93. if err := client.Incr("counter").Err(); err != nil {
  94. panic(err)
  95. }
  96. n, err := client.Get("counter").Int64()
  97. fmt.Println(n, err)
  98. // Output: 1 <nil>
  99. }
  100. func ExampleClient_BLPop() {
  101. if err := client.RPush("queue", "message").Err(); err != nil {
  102. panic(err)
  103. }
  104. // use `client.BLPop(0, "queue")` for infinite waiting time
  105. result, err := client.BLPop(1*time.Second, "queue").Result()
  106. if err != nil {
  107. panic(err)
  108. }
  109. fmt.Println(result[0], result[1])
  110. // Output: queue message
  111. }
  112. func ExampleClient_Scan() {
  113. client.FlushDb()
  114. for i := 0; i < 33; i++ {
  115. err := client.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
  116. if err != nil {
  117. panic(err)
  118. }
  119. }
  120. var cursor uint64
  121. var n int
  122. for {
  123. var keys []string
  124. var err error
  125. keys, cursor, err = client.Scan(cursor, "", 10).Result()
  126. if err != nil {
  127. panic(err)
  128. }
  129. n += len(keys)
  130. if cursor == 0 {
  131. break
  132. }
  133. }
  134. fmt.Printf("found %d keys\n", n)
  135. // Output: found 33 keys
  136. }
  137. func ExampleClient_Pipelined() {
  138. var incr *redis.IntCmd
  139. _, err := client.Pipelined(func(pipe *redis.Pipeline) error {
  140. incr = pipe.Incr("pipelined_counter")
  141. pipe.Expire("pipelined_counter", time.Hour)
  142. return nil
  143. })
  144. fmt.Println(incr.Val(), err)
  145. // Output: 1 <nil>
  146. }
  147. func ExampleClient_Pipeline() {
  148. pipe := client.Pipeline()
  149. incr := pipe.Incr("pipeline_counter")
  150. pipe.Expire("pipeline_counter", time.Hour)
  151. // Execute
  152. //
  153. // INCR pipeline_counter
  154. // EXPIRE pipeline_counts 3600
  155. //
  156. // using one client-server roundtrip.
  157. _, err := pipe.Exec()
  158. fmt.Println(incr.Val(), err)
  159. // Output: 1 <nil>
  160. }
  161. func ExampleClient_TxPipelined() {
  162. var incr *redis.IntCmd
  163. _, err := client.TxPipelined(func(pipe *redis.Pipeline) error {
  164. incr = pipe.Incr("tx_pipelined_counter")
  165. pipe.Expire("tx_pipelined_counter", time.Hour)
  166. return nil
  167. })
  168. fmt.Println(incr.Val(), err)
  169. // Output: 1 <nil>
  170. }
  171. func ExampleClient_TxPipeline() {
  172. pipe := client.TxPipeline()
  173. incr := pipe.Incr("tx_pipeline_counter")
  174. pipe.Expire("tx_pipeline_counter", time.Hour)
  175. // Execute
  176. //
  177. // MULTI
  178. // INCR pipeline_counter
  179. // EXPIRE pipeline_counts 3600
  180. // EXEC
  181. //
  182. // using one client-server roundtrip.
  183. _, err := pipe.Exec()
  184. fmt.Println(incr.Val(), err)
  185. // Output: 1 <nil>
  186. }
  187. func ExampleClient_Watch() {
  188. var incr func(string) error
  189. // Transactionally increments key using GET and SET commands.
  190. incr = func(key string) error {
  191. err := client.Watch(func(tx *redis.Tx) error {
  192. n, err := tx.Get(key).Int64()
  193. if err != nil && err != redis.Nil {
  194. return err
  195. }
  196. _, err = tx.Pipelined(func(pipe *redis.Pipeline) error {
  197. pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
  198. return nil
  199. })
  200. return err
  201. }, key)
  202. if err == redis.TxFailedErr {
  203. return incr(key)
  204. }
  205. return err
  206. }
  207. var wg sync.WaitGroup
  208. for i := 0; i < 100; i++ {
  209. wg.Add(1)
  210. go func() {
  211. defer wg.Done()
  212. err := incr("counter3")
  213. if err != nil {
  214. panic(err)
  215. }
  216. }()
  217. }
  218. wg.Wait()
  219. n, err := client.Get("counter3").Int64()
  220. fmt.Println(n, err)
  221. // Output: 100 <nil>
  222. }
  223. func ExamplePubSub() {
  224. pubsub, err := client.Subscribe("mychannel1")
  225. if err != nil {
  226. panic(err)
  227. }
  228. defer pubsub.Close()
  229. err = client.Publish("mychannel1", "hello").Err()
  230. if err != nil {
  231. panic(err)
  232. }
  233. msg, err := pubsub.ReceiveMessage()
  234. if err != nil {
  235. panic(err)
  236. }
  237. fmt.Println(msg.Channel, msg.Payload)
  238. // Output: mychannel1 hello
  239. }
  240. func ExamplePubSub_Receive() {
  241. pubsub, err := client.Subscribe("mychannel2")
  242. if err != nil {
  243. panic(err)
  244. }
  245. defer pubsub.Close()
  246. n, err := client.Publish("mychannel2", "hello").Result()
  247. if err != nil {
  248. panic(err)
  249. }
  250. fmt.Println(n, "clients received message")
  251. for i := 0; i < 2; i++ {
  252. // ReceiveTimeout is a low level API. Use ReceiveMessage instead.
  253. msgi, err := pubsub.ReceiveTimeout(5 * time.Second)
  254. if err != nil {
  255. break
  256. }
  257. switch msg := msgi.(type) {
  258. case *redis.Subscription:
  259. fmt.Println("subscribed to", msg.Channel)
  260. case *redis.Message:
  261. fmt.Println("received", msg.Payload, "from", msg.Channel)
  262. default:
  263. panic(fmt.Errorf("unknown message: %#v", msgi))
  264. }
  265. }
  266. // Output: 1 clients received message
  267. // subscribed to mychannel2
  268. // received hello from mychannel2
  269. }
  270. func ExampleScript() {
  271. IncrByXX := redis.NewScript(`
  272. if redis.call("GET", KEYS[1]) ~= false then
  273. return redis.call("INCRBY", KEYS[1], ARGV[1])
  274. end
  275. return false
  276. `)
  277. n, err := IncrByXX.Run(client, []string{"xx_counter"}, 2).Result()
  278. fmt.Println(n, err)
  279. err = client.Set("xx_counter", "40", 0).Err()
  280. if err != nil {
  281. panic(err)
  282. }
  283. n, err = IncrByXX.Run(client, []string{"xx_counter"}, 2).Result()
  284. fmt.Println(n, err)
  285. // Output: <nil> redis: nil
  286. // 42 <nil>
  287. }
  288. func Example_customCommand() {
  289. Get := func(client *redis.Client, key string) *redis.StringCmd {
  290. cmd := redis.NewStringCmd("GET", key)
  291. client.Process(cmd)
  292. return cmd
  293. }
  294. v, err := Get(client, "key_does_not_exist").Result()
  295. fmt.Printf("%q %s", v, err)
  296. // Output: "" redis: nil
  297. }
  298. func ExampleScanIterator() {
  299. iter := client.Scan(0, "", 0).Iterator()
  300. for iter.Next() {
  301. fmt.Println(iter.Val())
  302. }
  303. if err := iter.Err(); err != nil {
  304. panic(err)
  305. }
  306. }
  307. func ExampleScanCmd_Iterator() {
  308. iter := client.Scan(0, "", 0).Iterator()
  309. for iter.Next() {
  310. fmt.Println(iter.Val())
  311. }
  312. if err := iter.Err(); err != nil {
  313. panic(err)
  314. }
  315. }