Spring Feign超时如何设置

本文小编为大家详细介绍“Spring Feign超时如何设置”,内容详细,步骤清晰,细节处理妥当,希望这篇“Spring Feign超时如何设置”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

Feign其他功能-超时设置

  • Feign 底层依赖于 Ribbon 实现负载均衡和远程调用。

  • Ribbon默认1秒超时。

超时配置:

ribbon:

ConnectTimeout: 1000 #连接超时时间,毫秒

ReadTimeout: 1000 #逻辑处理超时时间,毫秒

Spring Feign超时如何设置

在feign-consumer中设置超时时间

server:
  port: 9000

eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: feign-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径

#设置Ribbon的超时时间
ribbon:
  ConnectTimeout: 1000 #链接超时时间,默认1s
  ReadTimeout: 3000 #逻辑处理的超时时间 默认1s

provider超时2s测试

Goods goods = goodsservice.findOne(id);
//当前现场睡眠2秒
try {
    Thread.sleep( millis: 2000);
}catch (InterruptedException e) {
    e.printStackTrace(); //java.net.SocketTimeoutException: Read timed out
}
goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置

Feign其他功能-日志记录

Feign 只能记录 debug 级别的日志信息。

logging: 
     level:   
          com.itheima: debug //包名

定义Feign日志级别Bean

@Bean
Logger.Level feignLoggerLevel() {    
		return Logger.Level.FULL;
		}

启用该Bean:

@FeignClient(configuration = XxxConfig.class)

Spring Feign超时如何设置

修改consumer

#设置当前的日志级别 debug,feign 只支持记录debug级别的日志
logging:
  level:
    com.itheima: debug

package com.itheima.consumer.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignLogConfig {
    /**
     * NONE, 不记录
     * BASIC, 记录基本的请求行,响应状态码数据
     * HEADERS, 记录基本的请求行,响应状态码数据,记录响应头信息
     * FULL 记录完整的请求,响应数据
     * @return
     */
    @Bean
    public Logger.Level level(){
        return Logger.Level.FULL;
    }
}
package com.itheima.consumer.feign;
import com.itheima.consumer.config.FeignLogConfig;
import com.itheima.consumer.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
 *  feign声明式接口 发钱远程调用的
 *   String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
 *         // 3. 调用方法
 *         Goods goods = restTemplate.getForObject(url, Goods.class);
 *
 *  1 定义接口
 *  2 接口上添加注解 @FeignClient 设置value属性为服务提供的 应用名称
 *  3 编写调用接口,接口的声明规则和提供方接口保持一致
 *  4 注入该接口对象,调用接口方法完成远程调用
 */
@FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
public interface GoodsFeignClient {
    @GetMapping("/goods/findOne/{id}")
    public Goods findGoodsById(@PathVariable("id") int id);
}

读到这里,这篇“Spring Feign超时如何设置”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程之家行业资讯频道。

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...