example_test.go 8.2 KB

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