照例附上项目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获取城市天气数据的接口。 @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的配置类。@Configurationpublic class RestConfiguration { @Autowired private RestTemplateBuilder builder; @Bean public RestTemplate restTemplate() { return builder.build(); } }请求结果: