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

标签 java struts2

我有一个用例,我的 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/

相关文章:

java - 将 id 值传递给操作类

java - struts2标签中的条件if

java - org.apache.struts2.json.annotations.JSON 没有显示正确的格式

java - Java Applet 中的键盘输入

java - JPA 连接在 Eclipse 中工作,但在编译时给出 NullPointerException

java - HTTP 状态 404 - 没有映射与上下文路径 [/struts2] 关联的命名空间 [/] 和操作名称 [login] 的操作

java - 在 Struts 2 中为特定操作映射配置 SiteMesh?

java - 使用 Keycloak 中的离线 cookie 实现单点登录 (SSO)

java - Java Concordion 子字符串 ("contains"的解决方法)

java - 如何在保持线程安全的同时降低锁定粒度?