123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package controllers
- import (
- "github.com/gin-gonic/gin"
- "go.uber.org/zap"
- "goiot-cronapi/common"
- "goiot-cronapi/models"
- "goiot-cronapi/pkg/logger"
- "goiot-cronapi/services"
- "goiot-cronapi/utils"
- "time"
- )
- // WeatherSample
- // 每15分钟采样一次天气接口数据
- // 从Redis中取出所有盒子对应的项目地区的天气信息
- // 如果取到了直接存入数据库中
- // 如果没取到则从接口拉取再同步到Redis, 最后再存到数据库中
- func WeatherSample(c *gin.Context) {
- var err error
- // 获取所有在线的盒子列表
- areaList := services.GetAreaList()
- logger.Info("采样城市数", zap.Int("NUM", len(areaList)))
- for _, area := range areaList {
- weather := services.GetWeatherFromRedis(area.CityId)
- if weather.CityId <= 0 || len(weather.Temp) <= 0 || len(weather.Humidity) <= 0 {
- go saveWeatherData(area)
- continue
- }
- // 直接存到数据库中
- if err = saveWeatherToDB(weather); err != nil {
- continue
- }
- }
- common.ReturnSuccess(c, nil)
- }
- // 请求天气数据并存入到Redis和数据库中
- func saveWeatherData(area *models.AreaModel) {
- // 从墨迹接口拉取天气数据
- condition, err := services.RequestCondition(area.CityId)
- if err == nil {
- if aqi, aqiErr := services.RequestAqi(area.CityId); aqiErr == nil {
- weather := models.Weather{
- CityId: area.CityId,
- Temp: condition.Data.Condition.Temp,
- Humidity: condition.Data.Condition.Humidity,
- Condition: condition.Data.Condition.Condition,
- Aqi: aqi.Data.Aqi.Value,
- AqiLevel: services.GetAirLevel(aqi.Data.Aqi.Value),
- PM25: aqi.Data.Aqi.PM25,
- Province: area.Province,
- City: area.City,
- Area: area.District,
- Icon: services.GetWeatherIcon(condition.Data.Condition.Condition),
- Created: time.Now().Format("2006-01-02 15:04:05"),
- }
- if len(weather.Area) <= 0 {
- weather.Area = area.Area
- }
- // 保存到Redis中
- if err = weather.SaveToRedis(); err != nil {
- logger.Info("更新Redis失败", zap.String("Error", err.Error()))
- }
- // 同时保存到数据库中
- if err = saveWeatherToDB(weather); err != nil {
- logger.Info("更新DB失败", zap.String("Error", err.Error()))
- }
- }
- }
- }
- func saveWeatherToDB(w models.Weather) error {
- sql := "INSERT INTO btk_runstat_weather(cityId, temp, humidity, pm25) VALUES(?, ?, ?, ?)"
- db, err := utils.OpenConnection()
- if err != nil {
- //common.ReturnSuccess(c, "db.err is:"+err.Error())
- //return
- }
- defer db.Close()
- return db.Exec(sql, w.CityId, w.Temp, w.Humidity, w.PM25).Error
- }
|