mr *_*gan 40 java tomcat batch-processing
有谁可以在这里提出建议?我有一种情况,用户将通过Java JSP和servlet以交互方式将数据挖掘请求提交给我的应用程序,该应用程序将动态地计算出关于数据的关联规则等.
因为这样的工作可能需要一段时间,我想在服务器上运行某种过程以在后台运行这样的请求,所以它不会"锁定"会话并可能使用大量的服务器内存而造成损害系统的.
由于系统由在MySQL数据库上运行在Tomcat容器中的一系列Java JSP和servlet组成,任何人都可以建议前进的方向吗?
谢谢
摩根先生
nos*_*nos 48
您应该做一些事情,将线程标记为守护程序线程,以便在错误情况下至少不会占用tomcat,并且应该在销毁servlet上下文时停止执行程序(例如,当您重新部署或停止应用程序时)要执行此操作,请使用ServletContextListener:
public class ExecutorContextListener implements ServletContextListener {
private ExecutorService executor;
public void contextInitialized(ServletContextEvent arg0) {
ServletContext context = arg0.getServletContext();
int nr_executors = 1;
ThreadFactory daemonFactory = new DaemonThreadFactory();
try {
nr_executors = Integer.parseInt(context.getInitParameter("nr-executors"));
} catch (NumberFormatException ignore ) {}
if(nr_executors <= 1) {
executor = Executors.newSingleThreadExecutor(daemonFactory);
} else {
executor = Executors.newFixedThreadPool(nr_executors,daemonFactory);
}
context.setAttribute("MY_EXECUTOR", executor);
}
public void contextDestroyed(ServletContextEvent arg0) {
ServletContext context = arg0.getServletContext();
executor.shutdownNow(); // or process/wait until all pending jobs are done
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Hands out threads from the wrapped threadfactory with setDeamon(true), so the
* threads won't keep the JVM alive when it should otherwise exit.
*/
public class DaemonThreadFactory implements ThreadFactory {
private final ThreadFactory factory;
/**
* Construct a ThreadFactory with setDeamon(true) using
* Executors.defaultThreadFactory()
*/
public DaemonThreadFactory() {
this(Executors.defaultThreadFactory());
}
/**
* Construct a ThreadFactory with setDeamon(true) wrapping the given factory
*
* @param thread
* factory to wrap
*/
public DaemonThreadFactory(ThreadFactory factory) {
if (factory == null)
throw new NullPointerException("factory cannot be null");
this.factory = factory;
}
public Thread newThread(Runnable r) {
final Thread t = factory.newThread(r);
t.setDaemon(true);
return t;
}
}
Run Code Online (Sandbox Code Playgroud)
您必须将上下文侦听器添加到web.xml,您还可以在其中指定要运行后台作业的线程数:
<listener>
<listener-class>com.example.ExecutorContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
您可以从servlet访问执行程序并向其提交作业:
ExecutorService executor = (ExecutorService )getServletContext().getAttribute("MY_EXECUTOR");
...
executor.submit(myJob);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Spring,那么所有这一切都可能变得更加简单
| 归档时间: |
|
| 查看次数: |
36547 次 |
| 最近记录: |