WeatherController.java 6.4 KB
package com.skua.modules.dataAnalysis.controller;

import com.alibaba.fastjson.JSONObject;
import com.skua.core.api.vo.Result;
import com.skua.core.aspect.annotation.AutoLog;
import com.skua.core.cache.RedisUtil;
import com.skua.core.service.IFactoryInfoService;
import com.skua.core.util.JwtUtil;
import com.skua.modules.dataAnalysis.service.IWeatherService;
import com.skua.modules.dataAnalysis.vo.ResultWeather;
import com.skua.modules.dataAnalysis.vo.WeatherNow;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "获取实时天气")
@RestController
@RequestMapping("/v1/weather")
public class WeatherController {

    @Autowired
    private RedisUtil redisUtil;
    private static String WeatherUrl = "https://devapi.qweather.com/v7/weather/now?";
    private static String KEY = "b480cc7cdc974e76bceb9b0bd06b64f1";
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX");
    @Autowired
    private IWeatherService weatherService;

    @AutoLog(value = "获取实时天气")
    @ApiOperation(value="获取实时天气", notes="获取实时天气")
    @GetMapping(value = "/getNowWeather")
    public Result<Map<String,Object>> getNowWeather(String factoryId) {
        Result<Map<String, Object>> result = new Result<>();
        Map<String, Object> map = new HashMap<>();
        ResultWeather resultWeather = new ResultWeather();
        Object object = redisUtil.get(factoryId + "_weather");
        if (object != null) {
            resultWeather = (ResultWeather)object;
        }else{
            Map<String, Object> locationMap = weatherService.getLocationByDepartId(factoryId);
            if(locationMap!=null){
                resultWeather = getNowWeatherData(locationMap.get("longitude").toString()+","
                        +locationMap.get("latitude").toString());
                resultWeather.setLocation(locationMap.get("city").toString());
            }
            setWeaterRedis(factoryId,resultWeather);
        }
        map.put("weatherData",resultWeather);
        result.setSuccess(true);
        result.setResult(map);
        return result;
    }

    //缓存天气入Redis
    private void setWeaterRedis(String factoryId, ResultWeather resultWeather) {
        //缓存天气入Redis
        redisUtil.set(factoryId + "_weather", resultWeather);
        // 设置超时时间
        redisUtil.expire(factoryId + "_weather", JwtUtil.EXPIRE_TIME / 1000);
    }

    public ResultWeather getNowWeatherData(String location) {
        ResultWeather resultWeather = new ResultWeather();
        String weatherResult = getDataByUrl(WeatherUrl,location);
        try{
            if (weatherResult != null) {
                JSONObject jsonObject = JSONObject.parseObject(weatherResult);
                JSONObject jsonWeater = JSONObject.parseObject(jsonObject.get("now").toString());
                String obsTime = jsonWeater.get("obsTime").toString();
                Date obsTimeDate = simpleDateFormat.parse(obsTime);
                jsonWeater.put("obsTime", obsTimeDate);
                WeatherNow weatherNow = JSONObject.toJavaObject(jsonWeater, WeatherNow.class);
                resultWeather.setHumidity(weatherNow.getHumidity());//湿度
                resultWeather.setWindDir(weatherNow.getWindDir());//风向
                resultWeather.setWindScale(weatherNow.getWindScale());//风力
                resultWeather.setTemp(weatherNow.getTemp());//温度
                resultWeather.setText(weatherNow.getText());//天气
                resultWeather.setIcon(weatherNow.getIcon());
                resultWeather.setObsTime(weatherNow.getObsTime());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultWeather;
    }

    private static String getDataByUrl(String url,String location) {
        String result = null;
        StringBuffer params = new StringBuffer();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("location=" + URLEncoder.encode(location, "utf-8"));
            params.append("&");
            params.append("key=" + KEY);
            // 创建Get请求
            HttpGet httpGet = new HttpGet(url + params);
            // 响应模型
            CloseableHttpResponse response = null;
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}