gpt4 book ai didi

java - 如何在重试 struts 操作之前 sleep ?

转载 作者:行者123 更新时间:2023-11-30 05:37:49 25 4
gpt4 key购买 nike

我有一个用例,我的 struts 操作从文件系统读取文件,然后在服务器响应中返回它。我想添加重试逻辑,让我的请求在重试读取文件之前 hibernate 一段时间,实现这一目标的最佳方法是什么?

我想在每次重试之间等待 1 秒后重试 10 次。我发现 Thread.sleep(1000) 使当前线程进入休眠状态。这是正确的方法吗?


public String execute()
{
for(int i = 0; i < 10; i++) {
// Read the file system
if (break_condition) {
break;
}
Thread.sleep(1000);
}
}

是否有更好的方法来实现这一目标?

最佳答案

最好不要在服务器上下文中使用 Thread.sleep ,因为它可能会产生不必要的影响。

建议的方法会有所不同,具体取决于可用的服务器和框架。然而,这个想法的核心是,您使用特定的 API 进行调度,或者在服务器提供的将来执行(重试)某些操作,并避免使用 Thread.sleep()

关键区别在于线程在继续操作之前不会 hibernate 并保持空闲状态。线程会在特定时间后通知服务器执行某些操作,然后线程将继续工作。

如果您处于 Java-EE 环境中,则 TimerService这将是一个好主意。它可以通过 TimerService.createSingleActionTimer() 来实现。

例如,如果您位于 Jave EE 服务器中,则可以执行以下操作:

import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Timer;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;

@Stateless
public class RetryWithWaitBean {


@Resource
private SessionContext context;

/**
*Create a timer that will be activated after the duration passes.
*/
public void doActionAfterDuration(long durationMillis) {
final TimerConfig timerConfig= new TimerConfig()
timerConfig.setPersistent(false);
context.getTimerService()..createSingleActionTimer(durationMillis,timerConfig);
}

/** Automatically executed by server on timer expiration.
*/
@Timeout
public void timeout(Timer timer) {
System.out.println("Trying after timeout. Timer: " + timer.getInfo());
//Do custom action
doAction();

timer.cancel();
}

/**
* Doing the required action
*/
private void doAction(){
//add your logic here. This code will run after your timer.
System.out.println("Action DONE!");
}
}

然后你就可以这样使用它:

 //This code should be in a managed context so that the server injects it.
@EJB
private RetryWithWaitBean retryWithWaitBean ;

然后就可以这样使用了。

//do an action after 3000 milliseconds
retryWithWaitBean.doActionAfterDuration(3000);

根据您使用的框架,有多种方法可以实现类似的结果。

关于java - 如何在重试 struts 操作之前 sleep ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com