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的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全 ...
随机推荐
- jquery几个按钮同时调用一个方法
- root-me web server 20-30 writeup
Remote File Inclusion-远程文件包含 Get the PHP source code. ctrl+u 进行RFI攻击需要同时具备三个条件(被攻击机器): allow_url_fop ...
- Nginx中修改php.ini的上传设置upload_max_filesize的值
普遍的网络越来越快,以前小家子气的2M上传限制慢慢变得不合时宜了.最近就把2M的限制直接提升到了20M...代码层面很快就修改好了,没什么可说的.但是上线的话还得修改一下服务器的配置.服务器是Ngin ...
- python判断字符串是否为空的方法s.strip()=='' if not s.strip():
python 判断字符串是否为空用什么方法? 复制代码 s=' ' if s.strip()=='': print 's is null' 或者 if not s.strip(): p ...
- liunx下安装mysql(未完待更新)
1.下载mysql-liunx 下载地址:http://download.csdn.net/download/yichen01010/10019139 2.删除系统自带mysql rpm -qa|gr ...
- 打开.py文件的方法
用IDLE打开这个文件,然后按F5,系统就自动开始运行这个python程序,然后当前运行目录就跳转到这个目录了
- css3兼容代码
1. 渐变:.gradient{ width:300px; height:150px; filter:alpha(opacity=100 finishopacity=50 style=1 startx ...
- Educational Codeforces Round 22 E. Army Creation 主席树 或 分块
http://codeforces.com/contest/813/problem/E 题目大意: 给出长度为n的数组和k, 大小是1e5级别. 要求在线询问区间[l, r]权值, 权值定义为对于 ...
- 《C++程序设计》朝花夕拾
(以后再也不用破Markdown写东西了,直到它有一个统一的标准,不然太乱了--) 函数签名 int f (int a, int b) ↑ ↑ ↑ ↑ 返回类型 函数名 形 式 参 数 其中,函数 ...
- 虚拟机安装Ubuntu过程记录
1.WMware中新建虚拟机 2.选择安装程序光盘镜像iso 3.个性化Linux(全名.用户名.密码等) 4.指定虚拟机名称以及安装位置 5.指定虚拟机磁盘容量大小 6.完成虚拟机配置 安装过程.. ...