Spring Cloud与Docker微服务架构实战(五)—— 使用Feign实现声明式REST调用

本文详细介绍了如何在Spring Cloud微服务架构中使用Feign进行声明式REST调用,包括整合Feign、自定义配置、手动创建Feign客户端、Feign对继承和压缩的支持,以及Feign的日志设置。通过实例展示了如何处理多参数请求,以及在需要认证的情况下调用服务。
摘要由CSDN通过智能技术生成

介绍

Feign是Netflix开发的声明式、模版化的HTTP客户端。

Feign使用简单,创建一个接口,并加上一些注解,代码就完成了。Feign支持多种注解,如自带的注解或JAX-RS注解等

为服务消费者整合Feign

1.复制项目microservice-simple-consumer-movie,将artifactId修改为microservice-simple-consumer-movie-feign

2.添加Feign依赖

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

3.创建一个Feign接口,并添加@FeignClient注解

import com.lzy.cloud.microservicesimpleconsumermovie.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name = "microservice-simple-provider-user")
public interface UserFeignClient {
   
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User findById(@PathVariable("id") Long id);
}

@FeignClient注解中的microservice-provider-user是一个任意的客户端名称,用于创建Ribbon负载均衡器。本例中,由于使用了Eureka,所以Ribbon会把microservice-provider-user解析成Eureka Server服务注册表中的服务。当然,如果不想使用Eureka,可使用service.ribbon.listOfServers属性配置服务器列表(见上一篇)

还可以使用url属性指定请求的URL(URL可以是完整的URL或主机名),如:

@FeignClient(name = "microservice-simple-provider-user", url = "http://localhost:8000/")

4.修改Controller代码,让其调用Feign接口

@RestController
public class MovieController {
   

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id){
   
        return this.userFeignClient.findById(id);
    }

}

5.修改启动类,为其添加@EnableFeignClient注解如下

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

启动eureka注册中心,启动多个用户微服务,启动feign调用的电影消费者微服务

多次访问http://localhost:8010/user/3,返回结果如下

{
   
"id": 3,
"username": "account3",
"name": "王五",
"age": 32,
"balance": 280
}

不但实现了声明式REST API调用,还实现了客户端侧的负载均衡

自定义Feign配置

在Spring Cloud中,Feign的默认配置类是FeignClientsConfiguration,该类定义了Feign默认使用的编码、解码器和所使用的契约等。

Spring Cloud允许通过注解@FeignClient的configuration属性自定义Feign的配置,自定义配置的优先级高于 FeignClientsConfiguration。

下面是Spring Cloud文档中描述的默认配置:

Spring Cloud Netflix provides the following beans by default for feign(BeanType beanName: ClassName):

  • Decoder feignDecoder: ResponseEntityDecoder(which wraps a SpringDecoder)
  • Encoder feignEncoder: SpringEncoder
  • Logger feignLogger: Slf4jLogger
  • Contract feignContract: SpringMvcContract
  • Feign.Builder feignBuilder: HystrixFeign.Builder
  • Client feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used

虽然Netflix没有为feign提供以下beans,但仍然可以从应用程序上下文中提取这些beans来创建client 客户端:

  • Logger.Level
  • Retryer
  • ErrorDecoder
  • Request.Options
  • Collection

在Spring Cloud中,Feign默认使用的契约是SpringMvcContract,因此它可以使用Spring MVC注解。下面来自定义Feign的配置,让它使用Feign自带的注解进行工作。

1.复制项目microservice-simple-consumer-movie-feign,将artifactID改为microservice-simple-consumer-movie-feign-customizing

2.创建Feign的配置类

import feign.Contract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
 * 该类不应该在 应用程序上下文的 @ComponentScan中
 */
@Configuration
public class FeignConfiguration {
   

    @Bean
    public Contract feignContract() {
   
        return new Contract.Default();
    }
}

3.Feign接口修改如下,使用@FeignClient的configuration属性指定配置类,同时,将findById上的Spring MVC注解修改为Feign自带的注解。

@FeignClient
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值