redis_go_cluster_adapter.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package redis
  2. import (
  3. "fmt"
  4. redisc "github.com/chasex/redis-go-cluster"
  5. "github.com/spf13/viper"
  6. "time"
  7. )
  8. // redis-go-cluster适配器
  9. type GoRedisClusterAdapter struct {
  10. cluster *redisc.Cluster
  11. }
  12. // 返回redis-go-cluster适配器新实例
  13. func NewGoRedisClusterAdapter(nodes []string) (IRedisAdapter, error) {
  14. maxActive := viper.GetInt("redis.max_active")
  15. idleTimeout := viper.GetDuration("redis.timeout")
  16. cluster, err := redisc.NewCluster(&redisc.Options{
  17. StartNodes: nodes,
  18. ConnTimeout: 5 * time.Second,
  19. KeepAlive: maxActive,
  20. AliveTime: idleTimeout,
  21. })
  22. if nil != err {
  23. return nil, err
  24. }
  25. return &GoRedisClusterAdapter{
  26. cluster: cluster,
  27. }, nil
  28. }
  29. // 关闭Redis连接
  30. func (a *GoRedisClusterAdapter) Close() error {
  31. a.cluster.Close()
  32. return nil
  33. }
  34. // 执行Redis命令
  35. func (a *GoRedisClusterAdapter) Do(commandName string, args ...interface{}) (interface{}, error) {
  36. return a.cluster.Do(commandName, args...)
  37. }
  38. // 返回命令管道操作对象
  39. func (a *GoRedisClusterAdapter) Pipeline() IRedisPipeline {
  40. return &GoRedisClusterPipeline{
  41. cluster: a.cluster,
  42. }
  43. }
  44. // Redigo命令管道操作对象
  45. type GoRedisClusterPipeline struct {
  46. cluster *redisc.Cluster
  47. commands []*redisCmd
  48. }
  49. // 向管道中添加命令
  50. func (p *GoRedisClusterPipeline) Send(commandName string, args ...interface{}) IRedisPipeline {
  51. p.commands = append(p.commands, &redisCmd{commandName: commandName, args: args})
  52. return p
  53. }
  54. // 执行管道中的命令
  55. func (p *GoRedisClusterPipeline) Execute() ([]interface{}, error) {
  56. if nil == p.commands || len(p.commands) == 0 {
  57. return nil, fmt.Errorf("no commands in pipeline")
  58. }
  59. batch := p.cluster.NewBatch()
  60. var err error
  61. for i := 0; i < len(p.commands); i++ {
  62. cmd := p.commands[i]
  63. err = batch.Put(cmd.commandName, cmd.args...)
  64. if nil != err {
  65. return nil, err
  66. }
  67. }
  68. return p.cluster.RunBatch(batch)
  69. }