package services import ( "encoding/json" "github.com/aiscrm/redisgo" "goiot-cronapi/common" "goiot-cronapi/models" "io/ioutil" "net/http" "strconv" "time" ) // GetWeatherFromRedis 从Redis中获取天气信息 func GetWeatherFromRedis(cityId int64) models.Weather { //内网地址:r-bp1g868m1d89jycev0487.redis.rds.aliyuncs.com //外网地址:r-bp1g868m1d89jycev0pd.redis.rds.aliyuncs.com rds, err := redisgo.New( redisgo.Options{ Addr: "r-bp1g868m1d89jycev0487.redis.rds.aliyuncs.com:6379", Password: "Meiyoumima1234", Prefix: "aiscrm_", }) if err != nil { panic(err) } var weather models.Weather key := "CITY:" + strconv.FormatInt(cityId, 10) exists, _ := rds.Exists(key) if !exists { return weather } data, _ := rds.GetString(key) if err := json.Unmarshal([]byte(data), &weather); err == nil { return weather } return weather } // RequestCondition 从墨迹天气接口获取天气信息 func RequestCondition(cityId int64) (*models.ConditionResp, error) { url := "http://aliv13.data.moji.com/whapi/json/alicityweather/condition?cityId=" + strconv.FormatInt(cityId, 10) req, err := http.NewRequest("POST", url, nil) if err != nil { return nil, err } req.Header.Set("Authorization", common.MJAppCode) client := &http.Client{Timeout: time.Second * 10} // Send request resp, err := client.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var cr models.ConditionResp if err := json.Unmarshal(body, &cr); err != nil { return nil, err } return &cr, nil } // RequestAqi 从墨迹天气接口获取空气质量 func RequestAqi(cityId int64) (*models.AqiResp, error) { url := "http://aliv13.data.moji.com/whapi/json/alicityweather/aqi?cityId=" + strconv.FormatInt(cityId, 10) req, err := http.NewRequest("POST", url, nil) if err != nil { return nil, err } req.Header.Set("Authorization", common.MJAppCode) client := &http.Client{Timeout: time.Second * 10} // Send request resp, err := client.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var ar models.AqiResp if err := json.Unmarshal(body, &ar); err != nil { return nil, err } return &ar, nil } func GetAirLevel(aqistr string) string { aqi, _ := strconv.Atoi(aqistr) level := "其他" if aqi > 0 && aqi <= 50 { level = "优" } else if aqi > 50 && aqi <= 100 { level = "良" } else if aqi > 100 && aqi <= 150 { level = "轻度污染" } else if aqi > 150 && aqi <= 200 { level = "中度污染" } else if aqi > 200 && aqi <= 300 { level = "重度污染" } else if aqi > 300 && aqi <= 500 { level = "严重污染" } else if aqi > 500 { level = "爆表" } return level } func GetWeatherIcon(condition string) string { iconName := common.WeatherIconMap[condition] return common.ConfigInfo.FileServUrl + "/moji/" + iconName + ".png" }