redisc_adapter.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package redis
  2. import (
  3. "github.com/gomodule/redigo/redis"
  4. "github.com/mna/redisc"
  5. "time"
  6. )
  7. // redisc适配器
  8. type RediscAdapter struct {
  9. cluster *redisc.Cluster
  10. }
  11. // 返回redisc适配器新实例
  12. func NewRediscAdapter(nodes []string) (IRedisAdapter, error) {
  13. opts := []redis.DialOption{
  14. redis.DialConnectTimeout(5 * time.Second),
  15. //redis.DialReadTimeout(5 * time.Second),
  16. //redis.DialWriteTimeout(5 * time.Second),
  17. }
  18. cluster := &redisc.Cluster{
  19. StartupNodes: nodes,
  20. DialOptions: opts,
  21. CreatePool: createPool,
  22. }
  23. return &RediscAdapter{
  24. cluster: cluster,
  25. }, nil
  26. }
  27. // 关闭Redis连接
  28. func (a *RediscAdapter) Close() error {
  29. return a.cluster.Close()
  30. }
  31. // 执行Redis命令
  32. func (a *RediscAdapter) Do(commandName string, args ...interface{}) (interface{}, error) {
  33. conn := a.cluster.Get()
  34. defer func(conn redis.Conn) {
  35. _ = conn.Close()
  36. }(conn)
  37. if nil == conn {
  38. return nil, ErrRedisConnNil
  39. } else {
  40. return conn.Do(commandName, args...)
  41. }
  42. }
  43. // 返回命令管道操作对象
  44. func (a *RediscAdapter) Pipeline() IRedisPipeline {
  45. return &RedigoPipeline{ // redisc库兼容redigo库,返回RedigoPipeline即可
  46. conn: a.cluster.Get(),
  47. }
  48. }