WeatherController.java
6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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;
}
}