【问题标题】:How to user Mojo::UserAgent's connect_timeout如何使用 Mojo::UserAgent 的 connect_timeout
【发布时间】:2016-03-29 22:25:50
【问题描述】:

这里是 Perl 新手。我有一行代码:

my $api_data = decode_json( $ua->get($url)->res->body );

在哪里$ua = Mojo::UserAgent->new。有时,请求可能会(无限期地)挂起,我想指定一个连接超时。

documentation 提供了一个示例,但我不确定如何将它正确地合并到我的声明中。

在这种情况下我应该如何使用connect_timeout?我知道 Mojo 指定了默认的连接超时值 (10),但我宁愿在代码中明确指定它。

【问题讨论】:

    标签: perl mojolicious mojo-useragent


    【解决方案1】:

    documentation 表明 connect_timeout 可以用作 getter 和 setter:

    my $timeout = $ua->connect_timeout;    # getter
    $ua         = $ua->connect_timeout(5); # setter
    

    setter 返回调用它的 Mojo::UserAgent 对象,以便它可以与其他方法链接。

    所以你可以这样做:

    my $ua = Mojo::UserAgent->new;
    
    my $api_data = decode_json( $ua->connect_timeout(42)->get($url)->res->body );
    

    但你不需要链接方法,所以我会推荐一个更易读的版本:

    my $ua = Mojo::UserAgent->new;
    $ua->connect_timeout(42);
    
    my $api_data = decode_json( $ua->get($url)->res->body );
    

    【讨论】:

    • 感谢您提供简单、直接的答案和可读性建议。
    猜你喜欢
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2015-12-09
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多