從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獲取城市天氣數據的接口。

    @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();
    }
    
}

請求結果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章