123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- package bootstrap
- import (
- "context"
- "designs/config"
- "designs/global"
- "fmt"
- "github.com/go-redis/redis/v8"
- "github.com/goccy/go-json"
- "go.uber.org/zap"
- "os"
- "strconv"
- "strings"
- )
- func InitializeRedis() *redis.Client {
- client := redis.NewClient(&redis.Options{
- Addr: config.Get("redis.host") + ":" + config.Get("redis.port"),
- Password: config.Get("redis.password"), // no password set
- DB: config.GetInt("redis.db"), // use default DB
- //Addr: "localhost:6379", // Redis 服务器地址和端口
- //Password: "", // Redis 访问密码,如果没有可以为空字符串
- //DB: 0, // 使用的 Redis 数据库编号,默认为 0
- })
- _, err := client.Ping(context.Background()).Result()
- if err != nil {
- global.App.Log.Error("Redis connect ping failed, err:", zap.Any("err", err))
- return nil
- }
- return client
- }
- func UnInitializeRedis(client *redis.Client) {
- if client != nil {
- client.Close()
- }
- }
- /* 初始游戏配置 */
- func InitGameCfg() {
- //判读本地有没有数据
- res, err := global.Redis().Exists(context.Background(), config.Get("app.province_table")).Result()
- if err != nil {
- global.App.Log.Error("InitGameCfg err")
- }
- if res != 1 {
- //不存在数据
- // 指定目录
- filePath := "./config/json/city.json"
- bytes, err := os.ReadFile(filePath)
- if err != nil {
- fmt.Println("os.ReadFile err=", err)
- }
- data := []interface{}{}
- json.Unmarshal(bytes, &data)
- // dat := data[0].(map[string]interface{})
- // fmt.Println(dat["hid"])
- cityData := make(map[string]interface{})
- for _, val := range data {
- res := val.(map[string]interface{})
- // fmt.Println(res["hid"], res["hname"])
- cityData[res["hname"].(string)] = res["hid"]
- }
- //设置数据
- global.App.Redis.HMSet(context.Background(), config.Get("app.province_table"), cityData)
- }
- }
- /* 通过ip地址获取地址code */
- func FindAddresscodeByIp(ip string) int {
- pro, _ := FindAddressByIp(ip)
- code := 999
- res, err := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
- if err != nil {
- return code
- }
- for key, val := range res {
- code, _ := strconv.Atoi(val)
- if strings.Contains(pro, key) {
- return code
- }
- }
- return code
- }
- /* 通过hid获取地址code */
- func FindAddresscodeByHid(hid int) (int, error) {
- res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
- for _, val := range res {
- code, _ := strconv.Atoi(val)
- if code == hid {
- return hid, nil
- }
- }
- return 0, redis.Nil
- }
- /* 通过hid获取地址 */
- func FindAddressByHid(hid int) string {
- res, _ := global.App.Redis.HGetAll(context.Background(), config.Get("app.province_table")).Result()
- for key, val := range res {
- code, _ := strconv.Atoi(val)
- if code == hid {
- return key
- }
- }
- return ""
- }
|