weather.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package controllers
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "go.uber.org/zap"
  5. "goiot-cronapi/common"
  6. "goiot-cronapi/global/orm"
  7. "goiot-cronapi/global/redis"
  8. "goiot-cronapi/models"
  9. "goiot-cronapi/pkg/logger"
  10. "goiot-cronapi/services"
  11. "time"
  12. )
  13. // WeatherSample
  14. // 每15分钟采样一次天气接口数据
  15. // 从Redis中取出所有盒子对应的项目地区的天气信息
  16. // 如果取到了直接存入数据库中
  17. // 如果没取到则从接口拉取再同步到Redis, 最后再存到数据库中
  18. func WeatherSample(c *gin.Context) {
  19. var err error
  20. // 获取所有在线的盒子列表
  21. areaList := services.GetAreaList(orm.Eloquent)
  22. logger.Info("采样城市数", zap.Int("NUM", len(areaList)))
  23. for _, area := range areaList {
  24. weather := services.GetWeatherFromRedis(redis.Cacher, area.CityId)
  25. if weather.CityId <= 0 || len(weather.Temp) <= 0 || len(weather.Humidity) <= 0 {
  26. go saveWeatherData(area)
  27. continue
  28. }
  29. // 直接存到数据库中
  30. if err = saveWeatherToDB(weather); err != nil {
  31. continue
  32. }
  33. }
  34. common.ReturnSuccess(c, nil)
  35. }
  36. // 请求天气数据并存入到Redis和数据库中
  37. func saveWeatherData(area *models.AreaModel) {
  38. // 从墨迹接口拉取天气数据
  39. condition, err := services.RequestCondition(area.CityId)
  40. if err == nil {
  41. if aqi, aqiErr := services.RequestAqi(area.CityId); aqiErr == nil {
  42. weather := models.Weather{
  43. CityId: area.CityId,
  44. Temp: condition.Data.Condition.Temp,
  45. Humidity: condition.Data.Condition.Humidity,
  46. Condition: condition.Data.Condition.Condition,
  47. Aqi: aqi.Data.Aqi.Value,
  48. AqiLevel: services.GetAirLevel(aqi.Data.Aqi.Value),
  49. PM25: aqi.Data.Aqi.PM25,
  50. Province: area.Province,
  51. City: area.City,
  52. Area: area.District,
  53. Icon: services.GetWeatherIcon(condition.Data.Condition.Condition),
  54. Created: time.Now().Format("2006-01-02 15:04:05"),
  55. }
  56. if len(weather.Area) <= 0 {
  57. weather.Area = area.Area
  58. }
  59. // 保存到Redis中
  60. if err = weather.SaveToRedis(redis.Cacher); err != nil {
  61. logger.Info("更新Redis失败", zap.String("Error", err.Error()))
  62. }
  63. // 同时保存到数据库中
  64. if err = saveWeatherToDB(weather); err != nil {
  65. logger.Info("更新DB失败", zap.String("Error", err.Error()))
  66. }
  67. }
  68. }
  69. }
  70. func saveWeatherToDB(w models.Weather) error {
  71. sql := "INSERT INTO btk_runstat_weather(cityId, temp, humidity, pm25) VALUES(?, ?, ?, ?)"
  72. return orm.Eloquent.Exec(sql, w.CityId, w.Temp, w.Humidity, w.PM25).Error
  73. }