package controllers import ( "github.com/gin-gonic/gin" "go.uber.org/zap" "goiot-cronapi/common" "goiot-cronapi/global/orm" "goiot-cronapi/global/redis" "goiot-cronapi/models" "goiot-cronapi/pkg/logger" "goiot-cronapi/services" "time" ) // WeatherSample // 每15分钟采样一次天气接口数据 // 从Redis中取出所有盒子对应的项目地区的天气信息 // 如果取到了直接存入数据库中 // 如果没取到则从接口拉取再同步到Redis, 最后再存到数据库中 func WeatherSample(c *gin.Context) { var err error // 获取所有在线的盒子列表 areaList := services.GetAreaList(orm.Eloquent) logger.Info("采样城市数", zap.Int("NUM", len(areaList))) for _, area := range areaList { weather := services.GetWeatherFromRedis(redis.Cacher, 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(redis.Cacher); 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(?, ?, ?, ?)" return orm.Eloquent.Exec(sql, w.CityId, w.Temp, w.Humidity, w.PM25).Error }