weather.go 2.5 KB

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