- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
仍然是 Scala 的新手,我现在正在寻找一种在其上实现以下代码的方法:
@Override
public void store(InputStream source, String destination, long size) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(size);
final PutObjectRequest request = new PutObjectRequest(
this.configuration.getBucket(), destination, source, metadata);
new RetryableService(3) {
@Override
public void call() throws Exception {
getClient().putObject(request);
}
};
}
在 Scala 中实现与 RetryableService 相同的功能的最佳方法是什么?
它基本上调用 call 方法 N 次,如果它们都失败,则引发异常,如果它们成功则继续。这个不返回任何东西,但是我有另一个版本允许返回一个值(所以,我在 Java 中有两个类),我相信我可以在 Scala 中使用单个类/函数。
有什么想法吗?
编辑
目前在java中的实现如下:
public abstract class RetryableService {
private static final JobsLogger log = JobsLogger
.getLogger(RetryableService.class);
private int times;
public RetryableService() {
this(3);
}
public RetryableService(int times) {
this.times = times;
this.run();
}
private void run() {
RuntimeException lastExceptionParent = null;
int x = 0;
for (; x < this.times; x++) {
try {
this.call();
lastExceptionParent = null;
break;
} catch (Exception e) {
lastExceptionParent = new RuntimeException(e);
log.errorWithoutNotice( e, "Try %d caused exception %s", x, e.getMessage() );
try {
Thread.sleep( 5000 );
} catch (InterruptedException e1) {
log.errorWithoutNotice( e1, "Sleep inside try %d caused exception %s", x, e1.getMessage() );
}
}
}
try {
this.ensure();
} catch (Exception e) {
log.error(e, "Failed while ensure inside RetryableService");
}
if ( lastExceptionParent != null ) {
throw new IllegalStateException( String.format( "Failed on try %d of %s", x, this ), lastExceptionParent);
}
}
public void ensure() throws Exception {
// blank implementation
}
public abstract void call() throws Exception;
}
最佳答案
递归 +
一等函数
按名称参数 == 真棒。
def retry[T](n: Int)(fn: => T): T = {
try {
fn
} catch {
case e =>
if (n > 1) retry(n - 1)(fn)
else throw e
}
}
用法是这样的:
retry(3) {
// insert code that may fail here
}
编辑:受@themel 启发的轻微变化的回答。少了一行代码:-)
def retry[T](n: Int)(fn: => T): T = {
try {
fn
} catch {
case e if n > 1 =>
retry(n - 1)(fn)
}
}
再次编辑:递归让我感到困扰,因为它向堆栈跟踪添加了几个调用。由于某种原因,编译器无法优化 catch 处理程序中的尾递归。但是,不在 catch 处理程序中的尾递归优化得很好:-)
@annotation.tailrec
def retry[T](n: Int)(fn: => T): T = {
val r = try { Some(fn) } catch { case e: Exception if n > 1 => None }
r match {
case Some(x) => x
case None => retry(n - 1)(fn)
}
}
再次编辑:显然,我打算将继续回来并为此答案添加替代方案作为一种爱好。这是一个尾递归版本,它比使用 Option
更简单,但使用 return
来短路函数并不是 Scala 惯用的。
@annotation.tailrec
def retry[T](n: Int)(fn: => T): T = {
try {
return fn
} catch {
case e if n > 1 => // ignore
}
retry(n - 1)(fn)
}
Scala 2.10 更新。作为我的爱好,我偶尔会重新审视这个答案。引入的 Scala 2.10 Try ,它提供了一种以尾递归方式实现重试的简洁方式。
// Returning T, throwing the exception on failure
@annotation.tailrec
def retry[T](n: Int)(fn: => T): T = {
util.Try { fn } match {
case util.Success(x) => x
case _ if n > 1 => retry(n - 1)(fn)
case util.Failure(e) => throw e
}
}
// Returning a Try[T] wrapper
@annotation.tailrec
def retry[T](n: Int)(fn: => T): util.Try[T] = {
util.Try { fn } match {
case util.Failure(_) if n > 1 => retry(n - 1)(fn)
case fn => fn
}
}
关于java - 实现像这样的可重试调用的 Scala 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930814/
是否可以重试网络客户端请求?在奇怪的情况下,我的应用程序在尝试连接到 xml Web 服务时会抛出错误,但如果我重试,它就可以正常工作。我希望它在抛出错误之前重试 2 次,除非有人有更好的解决方案:)
我在一本书中找到了这段代码片段: int ival; // read cin and test only for EOF; loop is executed even if there are oth
是否可以使用 for lop 来设置对象的条件。如果该条件未通过测试(if 语句),则更改条件直到它通过测试?这是我的伪代码尝试,但我怀疑它是否有效: for (int i = 0; i < myAr
我有以下问题。我的主要 Activity 由一个 ListView 组成,其中填充了从 Web 服务获得的数据。首次加载主要 Activity 时,以防无法从网络检索数据,我想显示一个带有 2 个按钮
我有微服务应用程序。为了协作,每个服务都使用异步消息传递。我知道,spring data jpa 默认使用乐观锁。但是如果这种锁定不是由用户调用,而是由另一个服务调用的方法(在我的示例中有验证服务,可
我希望能够在 F# 中编写一个计算表达式,如果它抛出异常,它将能够重试操作。现在我的代码看起来像: let x = retry (fun() -> GetResourceX()) let y = re
是否可以在 NServiceBus 版本 3.2.2 中禁用重试? 使用以下配置,可以禁用重试: 但当线程数设置为 20 时则不会。在这种情况下,消息会重试两次: 这看起来很像
我在 failed_jobs 上有多个失败的作业。我尝试重新排队 MaxAttemptsExceededException 但总是失败。如何重试那里的工作类型? 注意:每次我通过 php artisa
下面的 sproc 尝试向表中插入一行并生成一个随机 ID,用于在相应表上进行 PK。与随机生成的 ID 的冲突在 catch 块中处理,在那里再次重试/调用该过程。现在,这需要很长时间并导致死锁,因
我试图实现代码以使用“mocha-retry”重试失败的测试以下是示例。 describe(retries,' retries-',function () { var self = this;
我正在尝试通过 Azure 数据工厂将数据从 Azure 数据湖存储插入到 Azure 表。 Azure Data Lake 文件中的数据与最终 Azure 表接收器的架构相同。 ADF 管道包含从
是http.RoundTripper在 Go 中基于 HTTP 状态代码(例如 429)实现 http GET 请求重试机制的正确位置? 它在某种程度上“感觉正确”( Go Playground )并
使用 spring reactive WebClient,我使用了一个 API,如果响应状态为 500,我需要使用指数退避重试。但是在 Mono 类中,我没有看到任何以 Predicate 作为输入参
我一直在尝试编写 react native 的快速入门指南,但一直收到此错误 There appears to be trouble with your network connection. Ret
我正在尝试使用从我们心爱的堆栈溢出中获取的 Retry Monad: type RetryBuilder(max, sleep : TimeSpan) = member x.Return(
使用 spring reactive WebClient,我使用了一个 API,如果响应状态为 500,我需要使用指数退避重试。但是在 Mono 类中,我没有看到任何以 Predicate 作为输入参
我有一个由 C#.NET 4.0 开发的两层 Windows 窗体应用程序。在这个应用程序中,我读取文件内容并在数据访问层中创建实体列表,并将其返回到 GUI 层以在 GridView 中显示。在我当
如果有人问过这个问题,我深表歉意,但我已经做了很多搜索,但还没有找到与我的问题类似的问题。 在我的应用程序中,我有一个密码更改页面,如果某人是新用户或重置了他/她的密码,该页面就会触发。 问题是,一旦
想知道为什么我的 promise 正在解决但试图重试。 var getResultsStream = url => Rx.Observable.onErrorResumeNext( Rx.O
假设我有以下 Promise 链: var result = Promise.resolve(filename) .then(unpackDataFromFile) .then(tra
我是一名优秀的程序员,十分优秀!