项目源码地址:https://download.csdn.net/download/weixin_42950079/87190349
connectTimeout 防止由于服务器处理时间过长而阻止调用方。
readTimeout 从建立连接时开始应用,并在返回响应时间过长时触发。
import feign.Contract;
import feign.Logger;
import feign.Request;
import org.springframework.context.annotation.Bean;
/**
* 全局配置:加了@Configuration注解表示全局配置,对所有服务起作用
* 局部配置:不加@Configuration注解表示局部配置,只针对指定的一个服务起作用
*/
public class OpenFeignConfig {
// 日志级别配置
@Bean
public Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
// 契约配置
@Bean
public Contract feignContract(){
return new Contract.Default();
}
// 超时时间配置
@Bean
public Request.Options options(){
/**
* connectTimeoutMillis: 连接超时时间,默认2s
* readTimeoutMillis: 请求处理超时时间,默认5s
*/
return new Request.Options(3000, 2000);
}
}
日志级别、契约配置、超时时间等OpenFeign扩展内容)import com.cd.order8010.config.OpenFeignConfig;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(name = "stock-service", path = "/stock", configuration = OpenFeignConfig.class)
public interface StockFeignService {
// 声明要调用的rest接口对应的方法
@RequestMapping("/reduce")
public String reduce();
}
feign:
client:
config:
stock-service: # 这里写default就是全局配置。如果是写服务名称(如:stock-service),则是针对某个微服务的配置,即局部配置
connect-timeout: 3000 #连接超时时间,默认2s
read-timeout: 2000 #请求处理超时时间,默认5s
以服务A 调用 服务B为例:
连接超时时间 (connect-timeout):是指服务A去请求服务B的网络连接时间。
读取超时时间/请求处理超时时间(read-timeout):是指服务A连接上服务B后,服务B处理这个请求并做出响应的时间。
由于connectTimeout是网络连接,不方便进行测试。所以这里只测试readTimeout请求处理超时。
由于readTimeout是请求处理并返回响应超时,也就是发生在服务提供方(服务消费方去调用服务提供方的接口,服务提供方响应的接口处理该请求并做出响应的限制时间)。
由于上面设置的read-timeout是2秒,所以我们可以在服务提供方的相应接口中使用TimeUnit.SECONDS.sleep(3)让线程睡眠3秒来模拟请求处理超时。
@RestController
@RequestMapping("/stock")
public class StockController {
@Value("${server.port}")
String port;
@RequestMapping("/reduce")
public String reduce() throws InterruptedException {
// 睡眠3秒
TimeUnit.SECONDS.sleep(3);
System.out.println("扣减库存");
return "扣减库存" + port;
}
}

