2 Star 2 Fork 4

联犀/core

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
weatherReadLogic.go 2.43 KB
一键复制 编辑 原始数据 按行查看 历史
杨磊 提交于 2024-10-10 21:56 . feat: 更新mod
package commonlogic
import (
"context"
"encoding/json"
"fmt"
"gitee.com/unitedrhino/share/caches"
"gitee.com/unitedrhino/share/ctxs"
"gitee.com/unitedrhino/share/errors"
"gitee.com/unitedrhino/share/utils"
"github.com/parnurzeal/gorequest"
"time"
"gitee.com/unitedrhino/core/service/syssvr/internal/svc"
"gitee.com/unitedrhino/core/service/syssvr/pb/sys"
"github.com/zeromicro/go-zero/core/logx"
)
type WeatherReadLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewWeatherReadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WeatherReadLogic {
return &WeatherReadLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
type respType[t any] struct {
Code string `json:"code"`
Now t `json:"now"`
}
//var key = "b7de434f83c146e480d13ba6a565ce30"
func (l *WeatherReadLogic) WeatherRead(in *sys.WeatherReadReq) (*sys.WeatherReadResp, error) {
uc := ctxs.GetUserCtx(l.ctx)
if in.Position == nil && in.ProjectID == 0 {
in.ProjectID = uc.ProjectID
}
if in.ProjectID != 0 {
pi, err := l.svcCtx.ProjectCache.GetData(l.ctx, in.ProjectID)
if err != nil {
return nil, err
}
in.Position = &sys.Point{
Longitude: pi.Position.GetLongitude(),
Latitude: pi.Position.GetLatitude(),
}
}
cacheKey := fmt.Sprintf("sys:common:weather:%.2f:%.2f", in.Position.Latitude, in.Position.Longitude)
ret, err := caches.GetStore().GetCtx(l.ctx, cacheKey)
if ret != "" {
var rett sys.WeatherReadResp
json.Unmarshal([]byte(ret), &rett)
return &rett, nil
}
tc, err := l.svcCtx.TenantConfigCache.GetData(l.ctx, "")
if err != nil {
return nil, err
}
key := tc.WeatherKey
var (
weather respType[sys.WeatherReadResp]
air respType[sys.WeatherAir]
greq = gorequest.New().Retry(3, time.Second*2)
)
//参考: https://dev.qweather.com/
_, _, errs := greq.Get(fmt.Sprintf("https://devapi.qweather.com/v7/weather/now?location=%v,%v&key=%s",
in.Position.Longitude, in.Position.Latitude, key)).EndStruct(&weather)
if errs != nil {
return nil, errors.System.AddDetail(errs)
}
_, _, errs = greq.Get(fmt.Sprintf("https://devapi.qweather.com/v7/air/now?location=%v,%v&key=%s",
in.Position.Longitude, in.Position.Latitude, key)).EndStruct(&air)
if errs != nil {
return nil, errors.System.AddDetail(errs)
}
weather.Now.Air = &air.Now
caches.GetStore().SetexCtx(l.ctx, cacheKey, utils.MarshalNoErr(weather.Now), 60*60*1) //1个小时的有效期
return &weather.Now, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/unitedrhino/core.git
git@gitee.com:unitedrhino/core.git
unitedrhino
core
core
v0.2.3

搜索帮助

0d507c66 1850385 C8b1a773 1850385