简体   繁体   English

如何从 j2ee 中长时间运行的进程中获得即时响应?

[英]How can i get an immediate response from a long running process in j2ee?

I can't seem to find a solid answer anywhere.我似乎无法在任何地方找到可靠的答案。 I THINK i found one with respect to JMS but it was confusing.我想我找到了一个关于 JMS 的,但它令人困惑。

It really depends what stack of j2EE are you using?这真的取决于您使用的是什么 j2EE 堆栈? Is it just web, ejb layer or both?.它只是网络、ejb 层还是两者兼而有之? If we are talking about the web then you can use asynchronous servlet introduced in the newest Java EE specification, if you are using plain EJB's then the natural choice would be Messege driven beans (mentioned JMS).如果我们谈论的是 Web,那么您可以使用最新的 Java EE 规范中引入的异步 servlet,如果您使用的是普通 EJB,那么自然的选择将是 Messege 驱动的 bean(提到 JMS)。 You can of course design a custom solution where for example you send some data to process and then the j2ee application itself calls your application (with http request for example) to notify that its done running the job.您当然可以设计一个自定义解决方案,例如您发送一些数据进行处理,然后 j2ee 应用程序本身调用您的应用程序(例如使用 http 请求)以通知它已完成运行作业。 Possibilities are endless and if one is better than other always depends on the specific scenario.可能性是无止境的,如果一个比另一个更好总是取决于具体的情况。

If I understand correctly what you are talking about is the ability to start a task (that will take some time) then respond to the user while that task is still doing it's stuff.如果我理解正确的话,您正在谈论的是启动任务的能力(这将需要一些时间)然后在该任务仍在执行时响应用户。 Depending on your requirements it is really quite simple and you can use a plain old Java Thread to perform the operation.根据您的要求,它确实非常简单,您可以使用普通的旧 Java 线程来执行操作。

public class DoSillyCounting extends Thread {
    private volatile int counter;
    public int getCounter() { return counter; }
    public run() {
        while (counter < 10) {
            counter ++;
            try { Thread.sleep(1000); }
            catch (InterruptedException ie) { }
        }
    }
}

In your setup page you might do this: (session is an HttpSession)在您的设置页面中,您可以这样做:(会话是一个 HttpSession)

DoSillyCounting doSillyCounting = new DoSillyCounting();
doSillyCounting.start();
session.putValue("tenSecondsCounter", doSillyCounting);
/* Here you can respond to the user while the Thread is executing */

And in your status page you might do this:在您的状态页面中,您可以这样做:

DoSillyCounting doSillyCounting =
    (DoSillyCounting)session.getValue("tenSecondsCounter");
out.print(Integer.toString(doSillyCounting.getCounter());
if (doSillyCounting.isAlive()) {
    out.print("Still Working on it");
} else {
    out.print("Yippee, I finished");
}

Of course, this is a rather useless example and this model is not a good idea when you may have a large number of requests to satisfy, it would then be worth looking at a ThreadPool implementation or using something like JMS.当然,这是一个相当无用的示例,当您可能有大量请求要满足时,此模型不是一个好主意,那么值得查看 ThreadPool 实现或使用诸如 JMS 之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM