redis.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package bootstrap
  2. import (
  3. "context"
  4. "designs/config"
  5. "designs/global"
  6. "github.com/go-redis/redis/v8"
  7. "go.uber.org/zap"
  8. "strconv"
  9. "strings"
  10. )
  11. func InitializeRedis() *redis.Client {
  12. client := redis.NewClient(&redis.Options{
  13. Addr: config.Get("redis.host") + ":" + config.Get("redis.port"),
  14. Password: config.Get("redis.password"), // no password set
  15. DB: config.GetInt("redis.db"), // use default DB
  16. //Addr: "localhost:6379", // Redis 服务器地址和端口
  17. //Password: "", // Redis 访问密码,如果没有可以为空字符串
  18. //DB: 0, // 使用的 Redis 数据库编号,默认为 0
  19. })
  20. _, err := client.Ping(context.Background()).Result()
  21. if err != nil {
  22. global.App.Log.Error("Redis connect ping failed, err:", zap.Any("err", err))
  23. return nil
  24. }
  25. return client
  26. }
  27. func UnInitializeRedis(client *redis.Client) {
  28. if client != nil {
  29. client.Close()
  30. }
  31. }
  32. /* 通过ip地址获取地址code */
  33. func FindAddresscodeByIp(ip string) int {
  34. pro, _ := FindAddressByIp(ip)
  35. code := 999
  36. res, err := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  37. if err != nil {
  38. return code
  39. }
  40. for key, val := range res {
  41. code, _ := strconv.Atoi(val)
  42. if strings.Contains(pro, key) {
  43. return code
  44. }
  45. }
  46. return code
  47. }
  48. /* 通过hid获取地址code */
  49. func FindAddresscodeByHid(hid int) (int, error) {
  50. res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  51. for _, val := range res {
  52. code, _ := strconv.Atoi(val)
  53. if code == hid {
  54. return hid, nil
  55. }
  56. }
  57. return 0, redis.Nil
  58. }
  59. /* 通过hid获取地址 */
  60. func FindAddressByHid(hid int) string {
  61. res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  62. for key, val := range res {
  63. code, _ := strconv.Atoi(val)
  64. if code == hid {
  65. return key
  66. }
  67. }
  68. return ""
  69. }