nats-config-redis.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package comm
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "github.com/go-redis/redis/v8"
  9. )
  10. func createRedisClient(rediscnf string) (*redis.Client, error) {
  11. redisOps := strings.Split(rediscnf, "#")
  12. if len(redisOps) < 2 {
  13. return nil, fmt.Errorf("无效redis地址 需要127.0.0.1:16379#0#username#password当前 %s", rediscnf)
  14. }
  15. fmt.Println("redis-format addr => ", redisOps[0])
  16. db, err := strconv.Atoi(redisOps[1])
  17. if err != nil {
  18. return nil, errors.New("非法redis数据库 id")
  19. }
  20. connOption := &redis.Options{
  21. Addr: redisOps[0],
  22. DB: db, // use default DB
  23. }
  24. if len(redisOps) == 4 {
  25. connOption.Username = redisOps[2]
  26. connOption.Password = redisOps[3]
  27. }
  28. return redis.NewClient(connOption), err
  29. }
  30. func (bus *NatsBus) NewRedisFromConfig(redisConfKey string, timeout ...interface{}) (*redis.Client, error) {
  31. //127.0.0.1:16379#0#username#password
  32. rediscnf, err := bus.RequestConfig(redisConfKey)
  33. if err != nil {
  34. panic(err)
  35. }
  36. redisenv := os.Getenv("REDIS")
  37. if len(redisenv) > 0 {
  38. rediscnf = redisenv
  39. }
  40. fmt.Println("config rediscnf => ", rediscnf)
  41. fmt.Println("env rediscnf => ", redisenv)
  42. return createRedisClient(rediscnf)
  43. }
  44. func (bus *NatsBus) NewRedisFromConfigDev(redisConfKey string, timeout ...interface{}) (*redis.Client, error) {
  45. //127.0.0.1:16379#0#username#password
  46. rediscnf, err := bus.RequestConfigDev(redisConfKey)
  47. if err != nil {
  48. panic(err)
  49. }
  50. redisenv := os.Getenv("REDIS")
  51. if len(redisenv) > 0 {
  52. rediscnf = redisenv
  53. }
  54. fmt.Println("config rediscnf => ", rediscnf)
  55. fmt.Println("env rediscnf => ", redisenv)
  56. return createRedisClient(rediscnf)
  57. }