package com.weather.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weather.service.WeatherDataService;
import com.weather.vo.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private StringRedisTemplate redisTemplate;
private static final long TIME_OUT = 1800L; //redis超时时间为30分钟
private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
@Override
public WeatherResponse getDataByCityId(final String cityId) {
String uri = WEATHER_URI + "citykey=" + cityId;
return this.doGetWeather(uri);
}
@Override
public WeatherResponse getDataByCityName(final String cityName) {
String uri = WEATHER_URI + "city=" + cityName;
return this.doGetWeather(uri);
}
private WeatherResponse doGetWeather(String uri) {
ObjectMapper mapper = new ObjectMapper();
WeatherResponse resp = null;
String strBody = null;
// 先从缓存中查询数据
if (redisTemplate.hasKey(uri)) {
strBody = redisTemplate.opsForValue().get(uri);
} else {
// 缓存中没有就调用接口查询天气数据
ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
if (respString.getStatusCodeValue() == 200) {
strBody = respString.getBody();
}
// 把查询出来的数据写入缓存中
redisTemplate.opsForValue().set(uri,strBody,TIME_OUT,TimeUnit.SECONDS);
}
try {
resp = mapper.readValue(strBody, WeatherResponse.class);
} catch (IOException e) {
//e.printStackTrace();
log.error("Error!",e);
}
return resp;
}
/**
* 根据城市id来同步天气数据
*/
@Override
public void syncDataByCityId(String cityId) {
String uri = WEATHER_URI + "citykey=" + cityId;
this.saveWeatherDate(uri);
}
/**
* 把天气数据放入缓存中
*/
private void saveWeatherDate(String uri) {
String strBody = null;
ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
if (respString.getStatusCodeValue() == 200) {
strBody = respString.getBody();
}
// 把查询出来的数据写入缓存中
redisTemplate.opsForValue().set(uri,strBody,TIME_OUT,TimeUnit.SECONDS);
}
}
毕设项目:基于springboot的天气预报系统.zip
需积分: 5 189 浏览量
2023-08-07
21:46:17
上传
评论
收藏 44KB ZIP 举报
独处东汉
- 粉丝: 417
- 资源: 822
最新资源
- pixi.min.js 文件
- 数据流图数据流图数据流图数据流图数据流图.txt
- 西北工业大学软件工程或计算机专业程序设计III基础大作业第一题万年历
- k-means聚类算法k-means聚类算法k-means聚类算法k-means聚类算法.txt
- 简单的EA程序,均线趋势交易
- 电脑工具集(非常好用)
- python爬虫-10-where条件语句-范围查询.ev4.rar
- python爬虫-09-where条件语句-逻辑运算符.ev4.rar
- ubuntu安装nvidia显卡驱动ubuntu安装nvidia显卡驱动ubuntuubuntu安装nvidia显卡驱动.txt
- python爬虫-08-where条件语句-比较运算符.ev4.rar
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈