feature/ip优化

This commit is contained in:
吕翠丽
2025-06-17 16:50:28 +08:00
parent 5574b1ba4e
commit 6d3891390f
5 changed files with 132 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
package ip_tool
import (
"context"
"encoding/json"
"fmt"
"io"
@@ -15,12 +16,14 @@ import (
type HuaChenIpClient struct {
AppCode string
Host string
cache ICacheAdapter
}
func NewHuaChenIpClient(appCode string) *HuaChenIpClient {
func NewHuaChenIpClient(appCode string, cache ICacheAdapter) *HuaChenIpClient {
return &HuaChenIpClient{
AppCode: appCode,
Host: "https://c2ba.api.huachen.cn",
cache: cache,
}
}
@@ -87,6 +90,31 @@ func (h *HuaChenIpClient) GetIpInfo(ip string) (res *ApiResult, err error) {
return &apiResult, nil
}
func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string) (res *ApiResult, err error) {
getCache, err := h.cache.Get(ctx, h.ipKey(ip))
if err != nil {
return nil, errors.Wrapf(err, "获取缓存失败ip:%s", ip)
}
if getCache != nil {
return getCache, nil
}
info, err := h.GetIpInfo(ip)
if err != nil {
return nil, errors.Wrapf(err, "获取ip:%s信息失败", ip)
}
err = h.cache.Set(ctx, h.ipKey(ip), *info, 24*time.Hour)
if err != nil {
return nil, errors.Wrapf(err, "缓存ip:%s信息失败", ip)
}
res = info
return
}
// ipKey 生成Redis key
func (h *HuaChenIpClient) ipKey(ip string) string {
return fmt.Sprintf("ip:%s", ip)
}
type ApiResult struct {
Ret int `json:"ret"`
Msg string `json:"msg"`