栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java 8-重试方法,直到满足条件(间隔)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 8-重试方法,直到满足条件(间隔)

是的,这可以在Java 7中轻松完成,甚至可以使用Java 8进行更清洁的操作。

method
方法的参数应为
java.util.function.Supplier<T>
until
方法的参数应为
java.util.function.Predicate<T>

然后,您可以使用方法引用或lambda表达式来创建Poller,如下所示:

myMethodPoller.poll(pollDurationInteger, intervalInMillisecond)          .method(payment::getStatus)          .until (paymentStatus -> paymentStatus.getValue().equals("COMPLETED"))          .execute();

附带说明一下,如果您要使用Java 8,建议您使用

java.time.Duration
而不是整数来表示轮询持续时间和间隔。

我还建议您查看https://github.com/rholder/guava-
retrying
,这是您可能会使用的库。如果没有,这可能是您的API的良好灵感,因为它具有出色的流畅API。

编辑:对问题的更新之后,这是一个简单的实现。我剩下一些部分供您完成TODO。

import java.time.Duration;import java.util.function.Predicate;import java.util.function.Supplier;public class MethodPoller<T> {    Duration pollDurationSec;    int pollIntervalMillis;    private Supplier<T> pollMethod = null;    private Predicate<T> pollResultPredicate = null;    public MethodPoller() {    }    public MethodPoller<T> poll(Duration pollDurationSec, int pollIntervalMillis) {        this.pollDurationSec = pollDurationSec;        this.pollIntervalMillis = pollIntervalMillis;        return this;    }    public MethodPoller<T> method(Supplier<T> supplier) {        pollMethod = supplier;        return this;    }    public MethodPoller<T> until(Predicate<T> predicate) {        pollResultPredicate = predicate;        return this;    }    public T execute()    {        // TODO: Validate that poll, method and until have been called.        T result = null;        boolean pollSucceeded = false;        // TODO: Add check on poll duration        // TODO: Use poll interval        while (!pollSucceeded) { result = pollMethod.get(); pollSucceeded = pollResultPredicate.test(result);        }        return result;    }}

样品使用:

import static org.junit.Assert.assertTrue;import java.util.UUID;import org.junit.Test;public class MethodPollerTest{    @Test    public void test()    {        MethodPoller<String> poller = new MethodPoller<>();        String uuidThatStartsWithoneTwoThree = poller.method(() -> UUID.randomUUID().toString())         .until(s -> s.startsWith("123"))         .execute();        assertTrue(uuidThatStartsWithOneTwoThree.startsWith("123"));        System.out.println(uuidThatStartsWithOneTwoThree);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429028.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号