itemHistoryDataMaxMinByTimeLogic.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package logic
  2. import (
  3. "GtDataStore/common/xerr"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/pkg/errors"
  8. "time"
  9. "GtDataStore/app/cmd/organization/internal/svc"
  10. "GtDataStore/app/cmd/organization/pb"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. )
  13. type ItemHistoryDataMaxMinByTimeLogic struct {
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. logx.Logger
  17. }
  18. func NewItemHistoryDataMaxMinByTimeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ItemHistoryDataMaxMinByTimeLogic {
  19. return &ItemHistoryDataMaxMinByTimeLogic{
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. Logger: logx.WithContext(ctx),
  23. }
  24. }
  25. func (l *ItemHistoryDataMaxMinByTimeLogic) ItemHistoryDataMaxMinByTime(in *pb.ItemHistoryDataByTimeReq) (*pb.ItemHistoryDataMaxMinResp, error) {
  26. st, sterr := time.Parse("2006-01-02 15:04:05", in.Stime)
  27. et, eterr := time.Parse("2006-01-02 15:04:05", in.Etime)
  28. if sterr != nil || eterr != nil {
  29. return nil, errors.New("time parse error")
  30. }
  31. useCache, cacheKey := false, ""
  32. if et.Sub(st).Seconds() > 86400 {
  33. useCache = true
  34. std, etd := st.Format("2006-01-02"), et.Format("2006-01-02")
  35. cacheKey = fmt.Sprintf("datastore:cache:min:max:%d:%s:%s:%s", in.ProjectId, in.ItemName, std, etd)
  36. }
  37. if useCache {
  38. if s, err := l.svcCtx.Cache.Get(cacheKey); err == nil && s != "" {
  39. res := pb.ItemHistoryDataMaxMinResp{}
  40. if err = json.Unmarshal([]byte(s), &res); err != nil {
  41. l.svcCtx.Cache.Del(cacheKey)
  42. } else {
  43. return &res, nil
  44. }
  45. }
  46. }
  47. modelData, err := l.svcCtx.ItemHistoryData.QueryHistoryDataMaxMinByTime(l.ctx, in)
  48. if err != nil {
  49. return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "model QueryHistoryDataMaxMinByTime get data err:%v", err)
  50. }
  51. res := &pb.ItemHistoryDataMaxMinResp{
  52. MaxVal: modelData.MaxVal.Float64,
  53. MinVal: modelData.MinVal.Float64,
  54. AvgVal: modelData.AvgVal.Float64,
  55. }
  56. if useCache {
  57. if cacheValue, err := json.Marshal(res); err == nil {
  58. l.svcCtx.Cache.Setex(cacheKey, string(cacheValue), 86400)
  59. }
  60. }
  61. return res, nil
  62. }