第二篇 服务的消费-声明式调用(Feign)

    科技2022-07-10  117

    上一篇文章,讲述了如何通过RestTemplate+Ribbon去消费服务,这篇文章主要讲述如何通过Feign去消费服务

    一、Feign简介

    Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果

    简而言之:

    Feign 采用的是基于接口的注解Feign 整合了ribbon

     

    二、准备工作

    继续用上一节的工程, 启动eureka-server,端口为1111; 启动eureka-provide两次,端口分别为2222、2223

    三、创建一个feign的服务

    1、新建一个maven工程,取名为feign-consumer,在它的pom文件引入Feign的起步依赖spring-cloud-starter-feign、Eureka的起步依赖spring-cloud-starter-eureka、Web的起步依赖spring-boot-starter-web,代码如下:

    <?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"> <parent> <artifactId>my-springcloud</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>feign-consumer</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies> </project>

    2、配置文件 指定程序名为feign-consumer,端口号为3001,服务注册地址为http://localhost:1111/eureka/ ,代码如下:

    server: port: 3001 spring: application: name: feign-consumer eureka: client: serviceUrl: defaultZone: http://localhost:1111/eureka/

    3、在程序的启动类FeignConsumerApplication ,加上@EnableFeignClients注解开启Feign的功能:

    @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class FeignConsumerApplication { public static void main(String[] args) { SpringApplication.run(FeignConsumerApplication.class, args); } }

    4、定义一个feign接口,通过@ FeignClient(“服务名”) 来指定调用哪个服务。比如在代码中调用了service-hi服务的“/hello”接口,代码如下:

    @FeignClient(value = "client-provide") public interface FeignConsumerService { @RequestMapping(value = "/hello",method = RequestMethod.GET) String sayHiFromClientOne(); }

    在Web层的controller层对外暴露一个”/hi”的API接口,通过上面定义的Feign客户端FeignConsumerService来消费服务

    @RestController public class FeignConsumerController { @Autowired FeignConsumerService feignConsumerService; @RequestMapping(value = "/hi",method = RequestMethod.GET) public String sayHi(){ return feignConsumerService.sayHiFromClientOne(); } }

    启动程序,多次访问http://localhost:3001/hi 浏览器交替显示

    说明Feign与Ribbon的消费方式效果一样,通过轮询的方式实现了客户端的负载均衡,与Ribbon不同的是,通过Feign的方式我们只需要定义服务绑定的接口,以声明式的方式,简单的实现了服务的调用

    Processed: 0.012, SQL: 8