从0开始构建SpringCloud微服务(1)

照例附上项目github链接

本项目实现的是将一个简单的天气预报系统一步一步改造成一个SpringCloud微服务系统的过程,第一节将介绍普通天气预报系统的简单实现。


数据来源:

数据来源1:http://wthrcdn.etouch.cn/weather_mini?city=深圳

数据来源2:http://wthrcdn.etouch.cn/weather_mini?citykey=101280601

数据来源3:http://mobile.weather.com.cn/js/citylist.xml



数据格式

在这里插入图片描述

在这里插入图片描述

根据返回的数据格式在vo包下面创建pojo。
在这里插入图片描述


Service

创建WeatherDataService在其中提供如下接口:

1)根据城市Id获取城市天气数据的接口。

扫描二维码关注公众号,回复: 5344232 查看本文章
	@Override
	public WeatherResponse getDataByCityId(String cityId) {
		String url=WEATHER_URI+ "citykey=" + cityId;
		return this.doGetWeather(url);
	}

2)根据城市名称获取天气数据的接口。

	@Override
	public WeatherResponse getDataByCityName(String cityName) {
		String url = WEATHER_URI + "city=" + cityName;
		return this.doGetWeather(url);
	}

其中doGetWeather方法为抽离出来的请求天气数据的方法。

	private WeatherResponse doGetWeahter(String uri) {
 		ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);
		
		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;
		String strBody = null;
		
		if (respString.getStatusCodeValue() == 200) {
			strBody = respString.getBody();
		}

		try {
			resp = mapper.readValue(strBody, WeatherResponse.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return resp;
	}



Controller

在controller中分别提供根据城市id与名称获取天气数据的接口。

@RestController
@RequestMapping("/weather")
public class WeatherController {
	@Autowired
	private WeatherDataService weatherDataService;
	
	@GetMapping("/cityId/{cityId}")
	public WeatherResponse getWeatherByCityId(@PathVariable("cityId") String cityId) {
		return weatherDataService.getDataByCityId(cityId);
	}
	
	@GetMapping("/cityName/{cityName}")
	public WeatherResponse getWeatherByCityName(@PathVariable("cityName") String cityName) {
		return weatherDataService.getDataByCityName(cityName);
	}
}



配置

创建Rest的配置类。

@Configuration
public class RestConfiguration {
	
	@Autowired
	private RestTemplateBuilder builder;

	@Bean
	public RestTemplate restTemplate() {
		return builder.build();
	}
	
}



请求结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40955287/article/details/87897333