天气数据API微服务(springBoot-data)
项目结构图:
pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.csq.study</groupId>
<artifactId>sprigBoot-data</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
</project>
controller层
package com.csq.study.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.csq.study.service.WeatherDataService;
import com.csq.study.vo.WeatherResponse;
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Autowired
private WeatherDataService weatherDataService;
@GetMapping("/cityId/{cityId}")
//@PathVariable:标识从路径中获取参数
public WeatherResponse getWeatherByCityId(@PathVariable("cityId") String cityId) {
return weatherDataService.getDataByCityId(cityId);
}
@GetMapping("/cityName/{cityName}")
//@PathVariable:标识从路径中获取参数
public WeatherResponse getWeatherByCityName(@PathVariable("cityName") String cityName) {
return weatherDataService.getDataByCityName(cityName);
}
}
service接口以及实现类
package com.csq.study.service;
import com.csq.study.vo.WeatherResponse;
public interface WeatherDataService {
//根据城市ID查询天气数据
WeatherResponse getDataByCityId(String cityId);
//根据城市名称查询天气数据
WeatherResponse getDataByCityName(String cityName);
}
package com.csq.study.service;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.csq.study.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
private final static Logger logger=LoggerFactory.getLogger(WeatherDataService.class);
private static final String WEATHER_URI="http://wthrcdn.etouch.cn/weather_mini?";
private final Long TIME_OUT=1800L;
@Autowired
//对redis api的封装
private StringRedisTemplate stringRedisTemplate;
//@Autowired
//private RestTemplate restTemplate;
@Override
public WeatherResponse getDataByCityId(String cityId) {
String uri=WEATHER_URI + "citykey=" + cityId;
return this.doGetWeather(uri);
}
@Override
public WeatherResponse getDataByCityName(String cityName) {
String uri=WEATHER_URI + "city=" + cityName;
return this.doGetWeather(uri);
}
private WeatherResponse doGetWeather(String uri) {
String key=uri;
String strBody=null;
ObjectMapper mapper=new ObjectMapper();
WeatherResponse resp=null;
//ValueOperations类可通过get()获取缓存中的数据
ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
//先查缓存,缓存没有就抛出异常
if(!this.stringRedisTemplate.hasKey(key)) {
logger.info("不存在key"+key);
throw new RuntimeException("没有相应天气信息");
}else {
logger.info("存在key"+key+", value="+ops.get(key));
strBody=ops.get(key);
}
//用json反序列化成我们想要的数据
try {
/*
* strBody:要解析的参数内容,从respString获取
* WeatherResponse.class:要转成的对象类型
*/
resp=mapper.readValue(strBody,WeatherResponse.class);
}catch(IOException e) {
logger.error("Error!",e);
throw new RuntimeException("天气信息解析失败");
}
return resp;
}
}
vo类
Forecast 类
public class Forecast implements Serializable{
/**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = 1L;
private String date;//琪日期
private String high;//最高温度
private String fengxiang;//风向
private String low;//最低温度
private String fengli;//风力
private String type;//天气类型
省略get/set方法
Weather 类
public class Weather implements Serializable {
/**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = 1L;
private String city;
private String aqi;//
private String wendu;
private String ganmao;
private Yesterday yesterday;
private List<Forecast> forecast;
省略get/set方法
WeatherResponse 类
public class WeatherResponse implements Serializable{
/**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = 1L;
private Weather data; //消息数据
private String status; //消息状态
private String desc;//消息描述
省略get/set方法
Yesterday 类
public class Yesterday implements Serializable{
/**
* @Fields serialVersionUID : TODO
*/
private static final long serialVersionUID = 1L;
private String date;
private String high;
private String fx;
private String low;
private String fl;
private String type;
省略get/set方法
快速启动类:
@SpringBootApplication
@EnableScheduling
public class Aplication {
public static void main(String[] args) {
SpringApplication.run(Aplication.class, args);
}
}
配置文件:
#端口
server.port=8081
#应用名称
spring.application.name=springBoot-data
缓存没有消息会报:
我们启动前面定时任务那个项目(https://blog.csdn.net/FindHuni/article/details/88100589),将我们要查的城市id先存储一个缓存到redis中去,这样,我们在回头访问会出现下面的截图。
缓存有的话直接查出来: