redis.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package common
  2. import (
  3. "context"
  4. "designs/config"
  5. "designs/global"
  6. "encoding/json"
  7. "fmt"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "github.com/go-redis/redis/v8"
  12. "github.com/sirupsen/logrus"
  13. )
  14. /* 初始游戏配置 */
  15. func InitGameCfg() {
  16. //判读本地有没有数据
  17. res, err := global.App.Redis.Exists(context.Background(), config.Get("app.province_table")).Result()
  18. if err != nil {
  19. logrus.Error("InitGameCfg err")
  20. }
  21. if res != 1 {
  22. //不存在数据
  23. // 指定目录
  24. filePath := "./config/json/city.json"
  25. bytes, err := os.ReadFile(filePath)
  26. if err != nil {
  27. fmt.Println("os.ReadFile err=", err)
  28. }
  29. data := []interface{}{}
  30. json.Unmarshal(bytes, &data)
  31. // dat := data[0].(map[string]interface{})
  32. // fmt.Println(dat["hid"])
  33. cityData := make(map[string]interface{})
  34. for _, val := range data {
  35. res := val.(map[string]interface{})
  36. // fmt.Println(res["hid"], res["hname"])
  37. cityData[res["hname"].(string)] = res["hid"]
  38. }
  39. //设置数据
  40. global.App.Redis.HMSet(context.Background(), config.Get("app.province_table"), cityData)
  41. }
  42. }
  43. /* 通过ip地址获取地址code */
  44. func FindAddresscodeByIp(ip string) int {
  45. pro, _ := FindAddressByIp(ip)
  46. code := 999
  47. res, err := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  48. if err != nil {
  49. return code
  50. }
  51. for key, val := range res {
  52. code, _ := strconv.Atoi(val)
  53. if strings.Contains(pro, key) {
  54. return code
  55. }
  56. }
  57. return code
  58. }
  59. /* 通过hid获取地址code */
  60. func FindAddresscodeByHid(hid int) (int, error) {
  61. res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  62. for _, val := range res {
  63. code, _ := strconv.Atoi(val)
  64. if code == hid {
  65. return hid, nil
  66. }
  67. }
  68. return 0, redis.Nil
  69. }
  70. /* 通过hid获取地址 */
  71. func FindAddressByHid(hid int) string {
  72. res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
  73. for key, val := range res {
  74. code, _ := strconv.Atoi(val)
  75. if code == hid {
  76. return key
  77. }
  78. }
  79. return ""
  80. }