有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java阻止在我的应用程序中多次访问servlet

下面给出了配置为autosys作业的url。这将调用下面给出的servlet。有谁能建议我如何保护这个方法“psServiceWrapper.processHRFeed();”每次连续按此url(比如10次)时,通过不正确的数据修改不断调用此url。我希望一次只能访问一个线程

我知道我必须使用同步方法或块。。我不知道该怎么做。。因为我对线程不太熟悉

http://mydomain:11000/dorf/HRDORFScriptServlet?script=hrFeed


public class HRDORFScriptServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(HRDORFScriptServlet.class);
private final String script = "script";

@Override
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    // TODO Auto-generated method stub
    performTask(arg0, arg1);
}

@Override
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    // TODO Auto-generated method stub
    performTask(arg0, arg1);
}

 /** Execute the servlet.
 * 
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

    DorfUser dorfUser = DorfSessionUtils.getDorfUser(request.getSession());
    HRDorfFeedServiceWrapper psServiceWrapper = new HRDorfFeedServiceWrapper(dorfUser);
    String reqParam = request.getParameter(script);
    if(reqParam.equals("hrFeed")){
    try{
        psServiceWrapper.processHRFeed();           
    }
    catch(ServiceException se){
        log.error("Error While calling HRFeed Service : "+se.getMessage());
    }
    catch(Exception e){
        log.error("Error While calling HRFeed Service : "+e.getMessage());
    }

    }
 }

}


共 (2) 个答案

  1. # 1 楼答案

    synchronized(this){ 
     psServiceWrapper.processHRFeed();     
    }
    

    但这将导致瓶颈,因为servlet将在当前线程执行psServiceWrapper.processHRFeed();之前停止响应

    如果您使用的是Java5,也可以使用ReetrantLock

    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

       private final ReentrantLock lock = new ReentrantLock();//Declare it
    

    像下面那样使用它

     lock.lock();  // block until condition holds
     try {
       psServiceWrapper.processHRFeed();
     } finally {
       lock.unlock()
     }
    
  2. # 2 楼答案

    我将把psServiceWrapper.processHRFeed()的功能移到一个实现Runnable的简单类

    public class MyTask implements Runnable
    {
        public void run() 
        {
            psServiceWrapper.processHRFeed();
        }
    }
    

    然后创建一个固定线程池大小为1的ExecutorService

    ExecutorService psServiceRunner = Executors.newFixedThreadPool(1);
    

    每次调用servlet时,我都会将MyTask的一个实例发布到这个servlet

    psServiceRunner.execute(new MyTask());
    

    这将

    1. 不要阻止servlet调用程序
    2. 确保在任何时间点只有一个servlet可以运行该方法