OpenFign-超时实现
OpenFign调用超时实现步骤:
1.provider timeout处理 改controller
2.Consumer timeout处理 改service 和controller
3.改application.yml配置
OpenFign调用超时实现步骤:
1.provider timeout处理 改controller
@RestController @Slf4j public class PaymentController { @GetMapping(value = "/payment/feign/timeout") public String paymentFeignTimeout() { // 业务逻辑处理正确,但是需要耗费3秒钟 try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return serverPort; } }
2.Consumer timeout处理 改service 和controller
service
@Component @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService { @GetMapping(value = "/payment/feign/timeout") public String paymentFeignTimeout(); }
controller
@RestController
@Slf4j
public class OrderFeignController
{
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout()
{
// OpenFeign客户端一般默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
3.application.yml文件
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
openFeign解决服务间调用超时问题
解决
1、 新建配置类 ServiceFeignConfiguration
import feign.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceFeignConfiguration {
@Value("${service.feign.connectTimeout:60000}")
private int connectTimeout;
@Value("${service.feign.readTimeOut:60000}")
private int readTimeout;
@Bean
public Request.Options options() {
return new Request.Options(connectTimeout, readTimeout);
}
}
2、在需要使用 feign 的接口上使用配置
import com.landscape.landscape.service.user.config.ServiceFeignConfiguration;
import com.landscape.landscape.service.user.service.fallback.FeignImServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@Component
@FeignClient(value = "landscape-service-im", configuration = ServiceFeignConfiguration.class, fallback = FeignImServiceFallback.class)
public interface FeignImService {
@PostMapping("/im/user/import")
String importUser(@RequestBody String json);
}