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

请求结果:

在这里插入图片描述

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