烟草味道|SpringCloud微服务实战:城市数据API微服务的实现

城市数据API微服务的实现城市数据API微服务包含了城市数据查询组件 。 城市数据查询组件提供了城市数据查询的接口 。
城市数据由于不会经常被更新 , 属于静态数据 , 所以我们已经将ciylst.xml文件放置到resoures目录下 , 由我们的城市数据服务来读取里面的内容即可 。
在micro-weather-report应用的基础上 , 我们将对其进行逐步的拆分 , 形成-一个新的微服务msa-weather-city-server应用 。
烟草味道|SpringCloud微服务实战:城市数据API微服务的实现所需环境为了演示本例子 , 需要采用如下开发环境 。
JDK 8 。
Gradle 4.0 。
●Spring Boot Web Starter 2.0.0.M4 。
调整服务层代码在com.waylau.spring.cloud. weather.service包下 , 我们之前已经定义了该应用的城市数据服务接口CityDataService 。
public interface CityDataService {获取城市列表.@return@throws ExceptionList listCity() throws Exception;CityDataServiceImpl是对CityDataService接口的实现 , 保留之前的代码即可 。 package com. waylau . spring. cloud. weather .service;import java. io. BufferedReader;import java. io. InputStreamReader;import java.util.List;import org. springframework.core. io.ClassPathResource;import org. springframework.core. io. Resource;import org. springframework. stereotype. Service;import com. waylau. spring. cloud. weather .util. XmlBuilder;import com. waylau. spring. cloud. weather . vo.City;import com. waylau. spring. cloud. weather.vo.CityList;/**★城市数据服务.* @since 1.0.0 2017年10月23日* @author Way Lau*/@Servicepublic class CityDataService Impl implements CityDataService {@Overridepublic List listCity() throws Exception {//读取XML文件Resource resource = new ClassPathResource ("citylist. xml");Buf feredReader br = new BufferedReader (new InputStreamReader (re-source . getInputStream(), "utf-8")) ;StringBuffer buffer = new StringBuffer() ;String line = "";while ( (line = br. readLine()) != null) {buffer .append(line) ;br.close() ;// XML转为Java对象CityList cityList = (CityList) XmlBuilder . xmlStrToobject (CityList.class, buffer. toString()) ;return cityList. getCityList();}}除上述CityDataServicelmpl、CityDataService 外 , 其他服务层的代码都可以删除了 。
新增CityController用于返回所有城市的列表 。
@RestController@Reques tMapping ("/cities")public class CityController {@Autowiredprivate CityDataService cityDataService;@GetMappingpublic List listCity() throws Exception {return cityDataService.listCity() ;}}除上述CityController外 , 其他控制层的代码都可以删除了 。
烟草味道|SpringCloud微服务实战:城市数据API微服务的实现删除配置类和天气数据同步任务配置类RestConfiguration、 QuartzConfiguration 及任务类WeatherDataSyncJob 的代码都可以删除了 。
清理值对象清理值对象我们需要保留解析城市相关的类 , 其他值对象(除City、CityList外)都可以删除了 。
清理前端代码、配置及测试用例已经删除的服务接口的相关测试用例自然也是要一并 删除的 。
同时 , 之前所编写的页面HTML、JS文件也要一并 删除 。
最后 , 要清理Thymeleaf在application.properties文件中的配置 , 以及build.gradle 文件中的依赖 。


推荐阅读