Advertisement
zergon321

Redis cluster - Golang example

Feb 3rd, 2021
1,597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.73 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "strings"
  7.  
  8.     "github.com/go-redis/redis"
  9. )
  10.  
  11. func main() {
  12.     fmt.Println("Hello!")
  13.  
  14.     rdb := redis.NewClusterClient(&redis.ClusterOptions{
  15.         Addrs: []string{":6379", ":6380",
  16.             ":6381", "7379", ":7380", ":7381"},
  17.     })
  18.  
  19.     // Check if usual operations work.
  20.     err := rdb.SAdd(context.Background(),
  21.         "lol{a}", "suck", "my", "dick").Err()
  22.     handleError(err)
  23.  
  24.     set, err := rdb.SMembers(context.Background(),
  25.         "lol{a}").Result()
  26.     handleError(err)
  27.  
  28.     fmt.Println("lol{a}:", strings.Join(set, ", "))
  29.  
  30.     // Check if transactions work.
  31.     // Keys should have the same hashtag in {}
  32.     // in order to perform transactions and scripts on them.
  33.     tx := rdb.TxPipeline()
  34.  
  35.     err = tx.SAdd(context.Background(),
  36.         "kek{a}", "fuck", "shit").Err()
  37.     handleError(err)
  38.  
  39.     err = tx.SUnionStore(context.Background(),
  40.         "lol{a}", "kek{a}", "lol{a}").Err()
  41.     handleError(err)
  42.  
  43.     err = tx.Del(context.Background(),
  44.         "kek{a}").Err()
  45.     handleError(err)
  46.  
  47.     _, err = tx.Exec(context.Background())
  48.     handleError(err)
  49.  
  50.     err = tx.Close()
  51.     handleError(err)
  52.  
  53.     set, err = rdb.SMembers(context.Background(),
  54.         "lol{a}").Result()
  55.     handleError(err)
  56.  
  57.     fmt.Println("lol{a}:", strings.Join(set, ", "))
  58.  
  59.     // Check if Lua scripts work.
  60.     script := `redis.call('SADD', KEYS[1], ARGV[1], ARGV[2], ARGV[3])
  61.  
  62.                return redis.call('SMEMBERS', KEYS[1])`
  63.     data, err := rdb.Eval(context.Background(), script,
  64.         []string{"foo"}, "bar", "fizz", "buzz").Result()
  65.     handleError(err)
  66.  
  67.     elems := data.([]interface{})
  68.     set = make([]string, len(elems))
  69.  
  70.     for i, elem := range elems {
  71.         set[i] = elem.(string)
  72.     }
  73.  
  74.     fmt.Println("Set:", strings.Join(set, ", "))
  75. }
  76.  
  77. func handleError(err error) {
  78.     if err != nil {
  79.         panic(err)
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement