照例附上项目github链接本项目实现的是将一个简单的天气预报系统一步一步改造成一个SpringCloud微服务系统的过程,本节主要讲的是单块架构改造成微服务架构的过程,最终将原来单块架构的天气预报服务拆分为四个微服务:城市数据API微服务,天气数据采集微服务,天气数据API微服务,天气预报微服务。本章主要讲解城市数据API微服务的实现。各微服务的主要功能服务注册机制多个微服务之间获知对方的存在并进行通信,需要通过服务注册机制。当我们的微服务启动的时候,就会将信息注册到服务注册表或者服务注册中心中。中心可以通过心跳机制等感知服务的状态,并广播给其他的微服务。一个服务调用另一个服务,调用其他服务的服务称为服务的消费者,被调用的服务称为服务的提供者。城市数据API微服务的实现配置pom文件对原来单块架构的天气预报服务进行改进,去除多余的依赖,最终的pom文件如下:<?xml version=“1.0” encoding=“UTF-8”?><project xmlns=“http://maven.apache.org/POM/4.0.0" xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.demo</groupId> <artifactId>sifoudemo02</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sifoudemo02</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.7.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> <!– <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> –> </plugin> </plugins> </build> </project>提供接口在service中保留获取本地xml文件中城市列表的方法listCity。@Servicepublic class CityDataServiceImpl implements CityDataService{ @Override public List<City> listCity() throws Exception { Resource resource=new ClassPathResource(“citylist.xml”); BufferedReader br=new BufferedReader(new InputStreamReader(resource.getInputStream(), “utf-8”)); StringBuffer buffer=new StringBuffer(); String line=””; while((line=br.readLine())!=null) { buffer.append(line); } br.close(); CityList cityList=(CityList)XmlBuilder.xmlStrToOject(CityList.class, buffer.toString()); return cityList.getCityList(); }}在controller中保留获取城市列表的接口。@RestController@RequestMapping("/cities”)public class CityController { @Autowired private CityDataService cityDataService; //返回城市列表 @GetMapping public List<City>listCity()throws Exception{ return cityDataService.listCity(); }}测试结果