优化ip缓存
This commit is contained in:
parent
db27554374
commit
992f39109d
@ -19,11 +19,10 @@ type HuaChenIpClient struct {
|
|||||||
cache ICacheAdapter
|
cache ICacheAdapter
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHuaChenIpClient(appCode string, cache ICacheAdapter) *HuaChenIpClient {
|
func NewHuaChenIpClient(appCode string) *HuaChenIpClient {
|
||||||
return &HuaChenIpClient{
|
return &HuaChenIpClient{
|
||||||
AppCode: appCode,
|
AppCode: appCode,
|
||||||
Host: "https://c2ba.api.huachen.cn",
|
Host: "https://c2ba.api.huachen.cn",
|
||||||
cache: cache,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,13 +89,19 @@ func (h *HuaChenIpClient) GetIpInfo(ip string) (res *ApiResult, err error) {
|
|||||||
return &apiResult, nil
|
return &apiResult, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, ttl time.Duration) (res *ApiResult, err error) {
|
func (h *HuaChenIpClient) Set(cache ICacheAdapter) {
|
||||||
getCache, err := h.cache.Get(ctx, h.ipKey(ip))
|
h.cache = cache
|
||||||
if err != nil {
|
}
|
||||||
return nil, errors.Wrapf(err, "获取缓存失败,ip:%s", ip)
|
|
||||||
}
|
func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, opt ...time.Duration) (res *ApiResult, err error) {
|
||||||
if getCache != nil {
|
if h.cache != nil {
|
||||||
return getCache, nil
|
res, err = h.cache.Get(ctx, h.ipKey(ip))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrapf(err, "获取缓存失败,ip:%s", ip)
|
||||||
|
}
|
||||||
|
if res != nil {
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
res, err = h.GetIpInfo(ip)
|
res, err = h.GetIpInfo(ip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -109,9 +114,11 @@ func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, ttl
|
|||||||
return nil, errors.Wrapf(err, "无法将IP信息转换为JSON,ip:%s", ip)
|
return nil, errors.Wrapf(err, "无法将IP信息转换为JSON,ip:%s", ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = h.cache.Set(ctx, h.ipKey(ip), string(infoJson), ttl)
|
if len(opt) == 0 {
|
||||||
if err != nil {
|
err = h.cache.Set(ctx, h.ipKey(ip), string(infoJson), opt[0])
|
||||||
return nil, errors.Wrapf(err, "缓存ip:%s信息失败,", ip)
|
if err != nil {
|
||||||
|
return nil, errors.Wrapf(err, "缓存ip:%s信息失败,", ip)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user