0406-服务注册与发现-客户端feign-使用、配置、日志、timeout
官方地址:https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#spring-cloud-feign
一、概述
Feign是一个声明式Web服务客户端。它使编写Web服务客户端变得更容易。使用Feign创建一个接口并对其进行注释。它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。 Spring Cloud添加了对Spring MVC注释的支持,并且使用了Spring Web中默认使用的相同HttpMessageConverters。Spring Cloud将Ribbon和Eureka集成在一起,在使用Feign时提供负载均衡的http客户端。
源码地址:https://github.com/OpenFeign/feign
1.1、基础使用
1》添加pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2》启动类上添加注解
@SpringBootApplication
@EnableFeignClients
public class ComsumerMovieFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ComsumerMovieFeignApplication.class, args);
}
}
3》添加一个接口并为接口添加注解,调用用户服务
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
// @GetMapping("/sample/{id}")
@RequestMapping(method = RequestMethod.GET, value = "/movie/{id}")
public User findById(@PathVariable("id") Long id);
}
注意点:1、spring注解不能使用getMapping,需使用RequestMapping;2、@PathVariable必须添加参数;3、当服务接受参数是一个对象时候,此时默认会转化为post请求,及时接口写的是get请求【?待解决】
//请求不会成功,只要参数是复杂对象,即使指定了GET方法,feign依然会以post方法进行发送
@RequestMapping(method = RequestMethod.GET, value = "/get-user")
public User getUser(User user);
4》程序调用
@Autowired
private UserFeignClient userFeignClient; @GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return userFeignClient.findById(id);
}
执行post类似
参考代码:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign
1.2、覆写Feign的默认配置
1.2.1、概述
Spring Cloud的Feign支持中的一个中心概念是指定的客户端。
每个feign客户端都是整体的一部分,这些组件是一起工作以根据需要联系远程服务器,并且该组件具有一个名称,开发人员可以使用@FeignClient批注命名。
Spring Cloud使用FeignClientsConfiguration创建一个新的集合,作为每个指定客户端的ApplicationContext。这包含(除其他外)feign.Decoder,feign.Encoder和feign.Contract。
通过使用@FeignClient声明额外配置(在FeignClientsConfiguration之上),Spring Cloud可让您完全控制客户端
示例
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
注意事项:FooConfiguration 同RibbonConfiguration一致放包问题,参看:http://www.cnblogs.com/bjlhx/p/8859088.html
注意事项2:以前使用url可以不用,现在必须使用name
1.2.2、默认配置
Spring Cloud Netflix默认提供以下bean for feign(BeanType beanName:ClassName):
DecoderfeignDecoder:ResponseEntityDecoder(which wraps aSpringDecoder) 默认解码EncoderfeignEncoder:SpringEncoder 默认编码LoggerfeignLogger:Slf4jLogger 默认日志ContractfeignContract:SpringMvcContract 默认契约Feign.BuilderfeignBuilder:HystrixFeign.Builder 默认构建builderClientfeignClient: if Ribbon is enabled it is aLoadBalancerFeignClient, otherwise the default feign client is used. 默认client
通过将feign.okhttp.enabled或feign.httpclient.enabled分别设置为true并将它们放在类路径中,可以使用OkHttpClient和ApacheHttpClient feign客户端。当使用Apache或OkHttpClient使用OK HTTP时,可以通过提供ClosableHttpClient的bean来定制HTTP客户端。
1.2.3、非默认配置
Spring Cloud Netflix默认情况下不提供以下bean,但仍从应用程序上下文中查找这些类型的bean以创建假客户端:
Logger.LevelRetryerErrorDecoderRequest.OptionsCollection<RequestInterceptor>SetterFactory
1.2.4、开发
编写一个默认注解
@Configuration
public class Configuration1 {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
}
因为原默认注解使用spring的现在这里改用feign契约,故以下调用需要使用feign的注解RequestLine等
编写客户端调用
@FeignClient(name = "microservice-provider-user", configuration = Configuration1.class)
public interface UserFeignClient {
@RequestLine("GET /sample/{id}")
public User findById(@Param("id") Long id);
}
程序使用即可。
参看代码:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-customizing
1.2.5、如果请求eureka的接口如
@FeignClient(name = "xxxx", url = "http://localhost:8761/", configuration = Configuration2.class)
public interface FeignClient2 {
@RequestMapping(value = "/eureka/apps/{serviceName}")
public String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName);
}
因为eureka设置了权限此时访问失败
需增加配置类,Configuration2增加权限校验
@Configuration
public class Configuration2 {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "a123");
}
}
1.2.6、Feign请求/响应压缩
feign.compression.request.enabled=true
feign.compression.response.enabled=true
Feign请求压缩为您提供了类似于您为Web服务器设置的设置:
feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048
这些属性使您可以选择压缩媒体类型和最小请求阈值长度。
1.3、feign日志
为每个创建的Feign客户端创建一个记录器。默认情况下,记录器的名称是用于创建Feign客户端的接口的完整类名称。 Feign日志记录仅响应DEBUG级别。
application.yml.
logging.level.project.user.UserClient: DEBUG
注level是具体类路径。可能不生效,需要配置一下配置
您可以为每个客户端配置的Logger.Level对象告诉Feign要记录多少。选择是:
NONE, No logging (DEFAULT).BASIC, 只记录请求方法和URL以及响应状态码和执行时间。HEADERS, 记录基本信息以及请求和响应标头。FULL, 为请求和响应记录标题,正文和元数据。
例如,以下操作将Logger.Level设置为FULL:
@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
参看代码:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-customizing
1.4、Feign第一次启动timeout问题
hystrix默认1秒超时
方法一、可配置超时时间增加:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
方法二、关闭熔断超时
hystrix.command.default.execution.timeout.enabled: false
方法三、关闭熔断机制
feign.hystrix.enabled: false
可以参看:https://github.com/Netflix/Hystrix/wiki/Configuration
1.5、手动创建Feign客户端
@Import(FeignClientsConfiguration.class)
class FooController { private FooClient fooClient; private FooClient adminClient; @Autowired
public FooController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
this.fooClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "http://PROD-SVC"); this.adminClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "http://PROD-SVC");
}
}
1.6、feign源码实现过程
1、首先通过@EnabledFeignClients注解开启FeignClient的功能。主要是启动程序时开启对@FeignClient注解的包扫描
2、根据feign的规则实现接口,并在接口上面加上@FeignClient注解
3、程序启动后,进行包扫描,扫描所有的@FeignClient的注解的类,并将这些类放入Ioc容器。
4、当接口的方法被调用时,通过JDK的代理来生成具体的RequestTemplate模板对象
5、根据RequestTemplate再生成Http请求的Request对象。
6、Request对象交给Client去处理,其中Client的网络请求框架可以是HttpURLConnetion,HTTPClient和OkHttp等
7、最后Client被封装到LoadBlanceClient类,这个类结合类Ribbon做负载均衡。
0406-服务注册与发现-客户端feign-使用、配置、日志、timeout的更多相关文章
- Nacos服务注册与发现的2种实现方法!
Spring Cloud Alibaba 技术体系中的 Nacos,提供了两个重要的功能:注册中心(服务注册与发现)功能和配置中心功能. 其中注册中心解决了微服务调用中,服务提供者和服务调用者的解耦, ...
- Spring Cloud Alibaba Nacos 服务注册与发现功能实现!
Nacos 是 Spring Cloud Alibaba 中一个重要的组成部分,它提供了两个重要的功能:服务注册与发现和统一的配置中心功能. 服务注册与发现功能解决了微服务集群中,调用者和服务提供者连 ...
- SpringCloud Eureka服务注册及发现——服务端/客户端/消费者搭建
Eureka 是 Netflix 出品的用于实现服务注册和发现的工具. Spring Cloud 集成了 Eureka,并提供了开箱即用的支持.其中, Eureka 又可细分为 Eureka Serv ...
- springcloud之服务注册与发现(zookeeper注册中心)-Finchley.SR2版
新年第一篇博文,接着和大家分享springcloud相关内容:本次主要内容是使用cloud结合zookeeper作为注册中心来搭建服务调用,前面几篇文章有涉及到另外的eureka作为注册中心,有兴趣的 ...
- .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现
Tip: 此篇已加入.NET Core微服务基础系列文章索引 => Steeltoe目录快速导航: 1. 基于Steeltoe使用Spring Cloud Eureka 2. 基于Steelt ...
- Spring Cloud 系列之 Eureka 实现服务注册与发现
如果你对 Spring Cloud 体系还不是很了解,可以先读一下 Spring Cloud 都有哪些模块 Eureka 是 Netflix 开源的服务注册发现组件,服务发现可以说是微服务架构的核心功 ...
- springcloud之服务注册与发现
本次分享的是关于springcloud服务注册与发现的内容,将通过分别搭建服务中心,服务注册,服务发现来说明:现在北京这边很多创业公司都开始往springcloud靠了,可能是由于文档和组件比较丰富的 ...
- Eureka服务注册与发现
一.服务注册 注册Eureka的服务非常的简单,只需要引入spring-cloud-starter-netflix-eureka-client的jar包即可. <dependency> & ...
- Spring Cloud Eureka 实现服务注册与发现
微服务 是一种架构模式,跟具体的语言实现无关,微服务架构将业务逻辑分散到了各个服务当中,服务间通过网络层进行通信共同协作:这样一个应用就可以划分为多个服务单独来维护发布.构建一个可靠微服务系统是需要具 ...
- 一、springcloud服务注册、发现、调用(consul/eureka)
1.Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全 ...
随机推荐
- javascript断点设置和调试
JS调试必备的5个debug技巧http://www.jb51.net/article/47812.htm Chrome 中的 JavaScript 断点设置和调试技巧http://www.xuebu ...
- how to identify your .NET Framework version
scenario: when I try to install github-windows on my PC, got such error "lower .NET Framework V ...
- SecureCRT超级终端使用说明
SecureCRT超级终端使用说明 一.连接POS机 1.运行SecureCRT,选择‘文件’菜单,在下拉菜单中选择‘快速连接’菜单: 2.在弹出的对话框中按如下图选择参数: 3.POS端开机,且数据 ...
- 字符串的数字部分递增,如user00000001后面的数字部分递增+1
使用存储过程方式 bengin declare@namevarchar(50) set@name=(selectmax(right('user00000001',8<8是从后往前数,从1开始&g ...
- .NET程序调试技巧(一):快速定位异常的一些方法
作为一个程序员,解BUG是我们工作中常做的工作,甚至可以说解决问题能力是一个人工作能力的重要体现.因为这体现了一个程序员的技术水平.技术深度.经验等等. 那么在我们解决BUG的过程中,定位问题是非常重 ...
- Android上传图片(PHP服务器)
原理 Android客户端模拟一个HTTP的Post请求到服务器端,服务器端接收相应的Post请求后,返回响应信息给给客户端. PHP服务器 <?php move_uploaded_file($ ...
- boost诊断工具BOOST_ASSERT、BOOST_VERIFY、BOOST_STATIC_ASSERT
boost.assert提供的主要工具是BOOST_ASSERT宏,类似于C语言的assert,提供运行时的断言,但功能有所增强; 默认情况下,BOOST_ASSERT宏等同于assert宏: # d ...
- flask配置加载几种方式
方法一.直接配置 app.config['HOST']='xxx.a.com' print(app.config.get('HOST')) 方法二.通过环境变量加载配置 环境变量:export MyA ...
- js的实例方法和静态方法分析
var Person=function(){}; Person.say=function(){ console.log('I am a Person,I can say.') }; Person.pr ...
- Ubuntu系统-网络配置
网络配置 静态IP root@ubuntu:~# cat /etc/network/interfaces # This file describes the network interfaces av ...