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

栏目: Java · 发布时间: 5年前

内容简介:照例附上本项目实现的是将一个简单的天气预报系统一步一步改造成一个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

数据格式

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

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

根据返回的数据格式在vo包下面创建pojo。

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

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

请求结果:

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


以上所述就是小编给大家介绍的《从0开始构建SpringCloud微服务(1)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

深入理解SPARK

深入理解SPARK

耿嘉安 / 机械工业出版社 / 2016-1-1 / 99

《深入理解SPARK:核心思想与源码分析》结合大量图和示例,对Spark的架构、部署模式和工作模块的设计理念、实现源码与使用技巧进行了深入的剖析与解读。 《深入理解SPARK:核心思想与源码分析》一书对Spark1.2.0版本的源代码进行了全面而深入的分析,旨在为Spark的优化、定制和扩展提供原理性的指导。阿里巴巴集团专家鼎力推荐、阿里巴巴资深Java开发和大数据专家撰写。 本书分为......一起来看看 《深入理解SPARK》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具