美文网首页
超时机制汇总

超时机制汇总

作者: braveheart075 | 来源:发表于2018-08-31 00:16 被阅读0次

超时

超时按照种类来分,有两种:

  • 连接超时:connectiontimeout
  • 读取超时: readtimeout

超时按照方向来分,也有两种:

  • 客户端调用超时
  • 服务端超时

一般发生超时的情况都是在涉及到跨系统调用的场景。有网络请求,所以才会有超时。内部超时可能更多的是读取超时。因为在一台服务器,一个应用内部,方法阻塞,导致调用的读取超时。

对于超时的处理,我们一般如下处理方式:

我们的场景是:A系统调用B系统。我们需要考虑如下几种情况:

  • A在调用B的时候,网络出现异常
  • A在调用B的时候,B系统收到请求,处理超时,A迟迟收不到结果。

在以上两种情况下,我们分别做如下处理

  • 对于第一种情况,属于网络超时,这个时候B系统无能为力,A系统需要做一些超时的处理机制。即对connectiontimeout的异常做捕获处理。

我们在微服务架构中,一般会使用feignclient或者resttemplate来进行请求的发送,底层可能用的是httpclient或者OKhttp,http本质还是tcp,所以对于网络连接成功与否是有感知的。因此这两个通讯组件都封装了connectiontimetou异常。

对于调用方,你需要去考虑这个连接超时的异常。

  • 对于第二种情况,属于读取超时。那么和第一种情况一样,通讯组件能感知到这种情况,A系统的通讯组件,需要对这种异常做处理。

比较完美的处理方式是B系统也要考虑这种情况。打个俗气点的比方,你自己不是傻逼,但是你不能保证来调用你的人不是傻逼。所以,你要防止调用你的人没有做超时处理,他的连接一直和你保持,最后,他的系统连接无法释放,你的也是。你们两个系统都挂了。

所以,比较好的处理方式是B系统在某些可能会发生异常的接口层面增加超时机制。springcloud的hystrix就是用来做这个的。超时熔断,或者信号量累计请求,进行错误比例的熔断策略。这个是从被调用方的角度,来帮忙防止调用方未做读取超时处理导致两个系统都挂掉的一种补偿手段。B系统做了这个控制,那么随便上游系统是否傻逼,你都不用怕被上游拖挂了。

最后,奉上一段代码,feign-client和hystrix的:

@Service
@DefaultProperties(defaultFallback = "fallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
@Slf4j
public class DemoService {

    @Autowired DemoClient demoClient;

    public static AtomicInteger number = new AtomicInteger(0);

    public Optional<String> demo() {
        return Optional.ofNullable(demoClient.callDemo());
    }

    @HystrixCommand(commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000000"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
        @HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),
        @HystrixProperty(name = "fallback.enabled",value = "true")
    },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30"),
            @HystrixProperty(name = "maxQueueSize", value = "101"),
            @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
            @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
            @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
        })
    public String hystrixTest() {
        try {
            TimeUnit.SECONDS.sleep(6000);//为了测试execution.isolation.thread.timeoutInMilliseconds参数
        } catch (InterruptedException e) {
//            e.printStackTrace();
        }
        log.info("into service......");
        test();
        return "hystrix";
    }

    public String fallback() {
        log.info("into fallback....");
        return "fallback";
    }

    public void test() {
        int num = number.addAndGet(1);
        log.info("into test method,not throw exception...");
        if(num>5) {
            log.info("throw an exception....");
            throw new NullPointerException();
        }
    }

    ///////////////////测试默认的超时//////
    @HystrixCommand
    public String defaultTimeoutTest() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {

        }
        return "default timeout...";
    }

}

在application.yml文件中,对feign的重试关闭:

server:
  port: 8086
  host: localhost
spring:
  application:
    name: eureka-client
eureka:
  instance:
    hostname: eureka-client
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://${server.host}:8083/eureka/,http://${server.host}:8084/eureka/,http://${server.host}:8085/eureka/
    registry-fetch-interval-seconds: 30
    eureka-service-url-poll-interval-seconds: 10
ribbon:
  MaxAutoRetriesNextServer: -1
feign:
  okhttp:
    enabled: true
  compression:
    request:
      enabled: true # You may consider enabling the request or response GZIP compression for your Feign requests. You can do this by enabling one of the properties:
    response:
      enabled: true

在启动类中,A系统设置超时策略

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class,args);
    }

    @Bean
    Request.Options options() {
        return new Request.Options(1000*10,40*1000);
    }
}

相关文章

  • 超时机制汇总

    超时 超时按照种类来分,有两种: 连接超时:connectiontimeout 读取超时: readtimeout...

  • Java实现超时机制

    Java实现超时机制

  • Netty4(十二):实现心跳机制

    案例代码下载 Netty 超时机制介绍 Netty 为超时机制提供了几个关键类:IdleState 是一个枚举,它...

  • Okio 超时机制

    Okio中有同步超时和异步超时。 同步超时Timeout类 Timeout类提供了两个互补的控制机制来定义超时策略...

  • chan通道无阻塞读写

    通过time超时机制实现 使用如下:

  • Dubbo超时和重连机制

    dubbo启动时默认有重试机制和超时机制。超时机制的规则是如果在一定的时间内,provider没有返回,则认为本次...

  • Dubbo的超时和重连机制

    dubbo启动时默认有重试机制和超时机制。 超时机制的规则是如果在一定的时间内,provider没有返回,则认为本...

  • Netty 超时机制及心跳程序实现

    本文介绍了 Netty 超时机制的原理,以及如何在连接闲置时发送一个心跳来维持连接。 Netty 超时机制的介绍 ...

  • Netty 超时机制及心跳程序实现

    本文介绍了 Netty 超时机制的原理,以及如何在连接闲置时发送一个心跳来维持连接。 Netty 超时机制的介绍 ...

  • Hystrix超时实现机制

    HystrixCommand在执行的过程中如何探测超时,本篇主要对此进行介绍说明。 1.主入口:executeCo...

网友评论

      本文标题:超时机制汇总

      本文链接:https://www.haomeiwen.com/subject/zqujwftx.html