照例附上项目github连接java
本项目实现的是将一个简单的天气预报系统一步一步改形成一个SpringCloud微服务系统的过程。本章主要讲解微服务的消费。git
微服务的消费模式主要有:github
下面咱们主要讲解客户端发现模式,以及服务端发现模式。web
客户端发现模式的具体流程以下:算法
1)服务实例启动后,将本身的位置信息提交到服务注册表中。spring
2)客户端从服务注册表进行查询,来获取可用的服务实例。编程
3)客户端自行使用负载均衡算法从多个服务实例中选择出一个。app
服务端发现模式与客户端发现模式的区别在于:服务端发现模式的负载均衡由负载均衡器(独立的)来实现,客户端不须要关心具体调用的是哪个服务。负载均衡
下面咱们价格介绍一些常见的微服务的消费者。分布式
HttpClient是常见的微服务的消费者,它是Apache Jakarta Common 下的子项目,能够用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,而且它支持 HTTP协议最新的版本和建议。
Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。经过Spring Cloud的封装,可让咱们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。
Ribbon常与Eureka结合使用。在典型的分布式部署中,Eureka为全部的微服务提供服务注册,Ribbon提供服务消费的客户端,含有许多负载均衡的算法。
Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,经过编写简单的接口和插入注解,就能够定义好HTTP请求的参数、格式、地址等信息。
而Feign则会彻底代理HTTP请求,咱们只须要像调用方法同样调用它就能够完成服务请求及相关处理。Feign整合了Ribbon和Hystrix(关于Hystrix咱们后面再讲),可让咱们再也不须要显式地使用这两个组件。
总起来讲,Feign具备以下特性:
本节咱们主要讲解如何集成Feign,实现微服务的消费功能。
pom.xml配置文件,添加以下依赖。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
application.yml文件,添加以下配置
服务的名称与工程的名称一致,而且设置请求一个服务的connect与read的超时时间。
spring: application: name: micro-weather-eureka-client-feign eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ feign: client: config: feignName: connectTimeout: 5000 readTimeout: 5000
添加@EnableFeignClients注解,启动Feign功能。
package com.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.scheduling.annotation.EnableScheduling; //@ServletComponentScan(basePackages="com.demo.web.servlet") @SpringBootApplication @EnableDiscoveryClient @EnableScheduling @EnableFeignClients public class Sifoudemo02Application { public static void main(String[] args) { SpringApplication.run(Sifoudemo02Application.class, args); } }
建立一个Feign客户端,经过其CityClient的接口,能够调用城市数据API微服务mas-weather-city-eureka中的cities接口,返回城市列表。
package com.demo.service; import java.util.List; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.demo.vo.City; //建立一个Feign客户端 获取城市数据微服务中的城市列表信息 @FeignClient("msa-weather-city-eureka") public interface CityClient { @RequestMapping(value="/cities",method=RequestMethod.GET) List<City> listCity()throws Exception; }
@RestController public class CityController{ @Autowired private CityClient cityClient; @GetMapping("/cities") public List<City> listCity(){ List<City> cityList=cityClient.listCity();  return cityList; } }
先启动Eureka服务端,而后启动被请求的微服务——城市数据API微服务,最后启动Feign客户端。