feign 作为一个声明式的 Http Client 开源项目。在微服务领域,相比于传统的 apache httpclient 与在 spring 中较为活跃的 RestTemplate 更面向服务化,更易于使用。底层封装了 Jersey 与 CXF 分别用于 REsT 与 SOAP 的服务(对应有 JAX-RS 与 JAX-WS  API),当然也可以配置换成其它类似的实现,比如 OkHttp 、Ribbon 或者 Apache HC 等。

feign 基本用法及注解的使用看官方文档。下面介绍下 Spring Cloud 中的封装及实现细节(Spring Cloud 文档):

一、 基本用法

现有服务提供方:需要调用它的 createUser 方法

@RestController
@RequestMapping("/users")
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "/current", method = RequestMethod.GET)
public Principal getUser(Principal principal) {
return principal;
} @PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(method = RequestMethod.POST)
public void createUser(@Valid @RequestBody User user) {
userService.create(user);
}
}

使用 feign 构建消费服务方,遵循以下步骤:

引入 maven 依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

1. 启用:使用  @EnableFeignClients 注解启动 feign 模块基础功能(扫描 feign client包,使用默认或指定的相关配置等等)

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

2. 声明:使用 @FeignClient("app-name") 创建声明式的 HC:很简单配置下 service 名称/url 与 发出请求的路径就好了。

@FeignClient(name = "auth-service")
public interface AuthServiceClient { @RequestMapping(method = RequestMethod.POST, value = "/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user); }

3. 调用:上面的代码,相对于服务提供方,它是客户端服务消费方。相对于服务消费方自身,它上升到一个 service,因此我们可以在 service 层或 controller 层调用它:

@Service
public class AccountServiceImpl implements AccountService { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
private AuthServiceClient authClient; @Autowired
private AccountRepository repository; /**
* {@inheritDoc}
*/
@Override
public Account create(User user) { Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername()); // 调用feign HC服务
authClient.createUser(user); Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false); Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving); repository.save(account); log.info("new account has been created: " + account.getName()); return account;
} ...

  

二、feign 的相关配置(比如日志、hytrix  等)

配置方式有 3种:

1. 使用 JavaConfig 方式

配置类(这里建议不要加 @Configuration 注解,否则将变成全局配置)

public class FileConf {

    private final ObjectFactory<HttpMessageConverters> messageConverters;

    @Autowired
public FileConf(ObjectFactory<HttpMessageConverters> messageConverters) {
this.messageConverters = messageConverters;
} @Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}

调用端

@FeignClient(value = "service-thirdparty", configuration = FileConf.class)
@RequestMapping(value = "/storage")
public interface StorageClient {
/**
* 上传图片
*/
@RequestMapping(
value = "/imageUpload",
method = RequestMethod.POST,
consumes = MULTIPART_FORM_DATA_VALUE)
BusinessResult uploadImage(@RequestParam(value = "bucket") String bucket,
@RequestPart(value = "file", required = false) MultipartFile file);

2. 使用 application.yml

# To disable Hystrix in Feign
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
hystrix:
enabled: false # To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE logging.level.project.user.UserClient: DEBUG

  

注意事项:

① 如果 @Configuration的 JavaConfig 与 properties 配置同时存在,那么后者会覆盖前者。通过设定 feign.client.default-to-properties to false. 改变优先权。

② 只有开启 DEBUG级别的日志, feign 的log功能才会生效。

③ 如果 classpath 引入了 hytrix(如下),并且配置启用 hytrix(比如  feign.hystrix.enabled=true),那么默认会启用 circuit breaker 。

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

在 Spring Cloud Dalston 及之后的版本中,circuit breaker 是可选操作。需要使用 @EnableCircuitBreaker 手动开启。

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class Application {

扩展:使用断路器功能

声明:

@FeignClient(name = "statistics-service", fallback = StatisticsServiceClientFallback.class)
public interface StatisticsServiceClient { @RequestMapping(method = RequestMethod.PUT, value = "/statistics/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void updateStatistics(@PathVariable("accountName") String accountName, Account account); }

定义 hytrix:

@Component
public class StatisticsServiceClientFallback implements StatisticsServiceClient {
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsServiceClientFallback.class);
@Override
public void updateStatistics(String accountName, Account account) {
LOGGER.error("Error during update statistics for account: {}", accountName);
}
}

  

233

参考资料


https://github.com/sqshq/PiggyMetrics (完整示例)

Spring Cloud 组件 —— feign的更多相关文章

  1. Spring Cloud 整合 Feign 的原理

    前言 在 上篇 介绍了 Feign 的核心实现原理,在文末也提到了会再介绍其和 Spring Cloud 的整合原理,Spring 具有很强的扩展性,会把一些常用的解决方案通过 starter 的方式 ...

  2. spring cloud 使用feign 遇到问题

    spring cloud 使用feign 项目的搭建 在这里就不写了,本文主要讲解在使用过程中遇到的问题以及解决办法 1:示例 @RequestMapping(value = "/gener ...

  3. spring cloud(四) feign

    spring cloud 使用feign进行服务间调用 1. 新建boot工程 pom引入依赖 <dependency> <groupId>org.springframewor ...

  4. 跟我学SpringCloud | 第十九章:Spring Cloud 组件 Docker 化

    前面的文章<跟我学SpringCloud | 第十八篇:微服务 Docker 化之基础环境>我们介绍了基础环境系统和 JRE 的容器化,这一节我们介绍 Spring Cloud 组件的容器 ...

  5. spring cloud关于feign client的调用对象列表参数、设置header参数、多环境动态参数试配

    spring cloud关于feign client的调用 1.有些场景接口参数需要传对象列表参数 2.有些场景接口设置设置权限等约定header参数 3.有些场景虽然用的是feign调用,但并不会走 ...

  6. SpringCloud升级之路2020.0.x版-9.如何理解并定制一个Spring Cloud组件

    本系列为之前系列的整理重启版,随着项目的发展以及项目中的使用,之前系列里面很多东西发生了变化,并且还有一些东西之前系列并没有提到,所以重启这个系列重新整理下,欢迎各位留言交流,谢谢!~ 我们实现的 S ...

  7. spring cloud 组件图

    spring cloud 提供了一套微服务的框架. 上图就是微服务一些常用的组件. 1.EureKa 实现服务的注册和发现. 2.Ribbon 实现服务的调用(客户端实现负载均衡) 3.Feign 实 ...

  8. spring cloud 之 Feign 使用HTTP请求远程服务

    一.Feign 简介 在spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLCo ...

  9. Spring Cloud之Feign客户端调用工具

    feign介绍 Feign客户端是一个web声明式http远程调用工具,提供了接口和注解方式进行调用. Spring Cloud 支持 RestTemplate  Fetin Feign客户端实际开发 ...

随机推荐

  1. 手写代码 - java.util.List 相关

    1-ArrayList 访问元素,不能使用ArrayList[0]形式!!!! 必须使用ArrayList.get(0);

  2. centos7.6设置sftp服务

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议. CentOS自带 SSH 服务,直接配置即可 1. 查看ssh版本 sftp是基于ssh协议的,首先查看 ...

  3. c# 序列化效率比拼

    前言:作为开发人员,对象的序列化经常用到,特别是在现在前后端分离 采用json 交互 ,就将原来用过的几种方式总结了下,也算是做一个记录,顺便做了下性能测试. 1:内置 JavaScriptSeria ...

  4. gitlab 权限说明

    五.权限说明 Guest(匿名用户) - 创建项目.写留言薄 Reporter(报告人)- 创建项目.写留言薄.拉项目.下载项目.创建代码片 段 Developer(开发者)- 创建项目.写留言薄.拉 ...

  5. 解决python查询报%d format: a number is required, not str问题

    文章链接:https://blog.csdn.net/u011878172/article/details/72599120 [问题描述] 1.在一条查询语句中,查询条件既包含了整形又包含了字符串型, ...

  6. electron 热更新

    试用了下,electron 自带的热更新 并不是特别理想. 想自己处理下载更新文件.刚好看到了网上有一个比较好的处理方式.试了下效果还可以. 使用以下命令将此库包含在项目中: npm install ...

  7. nginx 10054报错问题解决方案

    使用nginx代理,端口8000.tomcat用于后端服务器,端口8080.nginx的error.log中报如下错误: 2018/09/21 09:08:06 [error] 12488#11600 ...

  8. ubuntu下 将证书导入java的cacerts证书库

    首先,说下java的cacerts证书库: JAVA_HOME目录下的jre的cacerts 主要的步骤有4个: 生成证书 导出证书 导入证书 生成证书(此处CN的值为localhost或者你想设置的 ...

  9. 大数据学习之HDFS基本API操作(上)06

    package it.dawn.HDFSPra; import java.io.FileNotFoundException; import java.io.IOException; import ja ...

  10. 课堂小记---JavaScript(2)

    本阶段难点疑点梳理 1.关于switch中default的使用: default同case功能一样,区别在于并不匹配任何信息,只有当case中无任何匹配的时候才会执行default.需要注意的是,这是 ...