【问题标题】:spring+jaxws: is there a better way than static variables to keep global status?spring+jaxws:有没有比静态变量更好的方法来保持全局状态?
【发布时间】:2015-06-18 19:01:35
【问题描述】:

我有一个 web 服务 (cxf),它在每次调用耗时的方法时创建一个新线程,向客户端返回一个 ID,作为令牌传递给另一个 web 方法以检查该特定线程的执行状态:

public String doWork(){
    String id = /***randomnly generates an ID****/
    executor.execute(**some runnable**);

   // need to save the guy above
   return id;
}

public String checkStatus(String id){
    /* Here I would basically access to an hashmap
       of tasks, pick the one identified by that ID
       and check its state */
}

正如您在上面看到的,我的问题是保留对任务的引用,以便我可以跟踪其执行情况。我想出的想法如下:

@Webservice
public class MyService{
    private static HashMap<String, Future> futures = new HashMap<String,Future>();

但是有更好的方法吗?此外,这种选择可能存在哪些缺点?

【问题讨论】:

    标签: spring cxf jax-ws


    【解决方案1】:

    另一种存储全局状态的方法是使用数据库。在不了解应用程序的所有细节的情况下,唯一想到的是,根据它们的使用方式,静态变量可能会出现线程安全问题。

    【讨论】:

    • 不,我不想使用数据库...耶稣 servlet 确实有一个应用程序上下文,我可以将数据保存在... jax ws 或 spring 不允许这样的事情?
    【解决方案2】:

    了解一些关于 Java EE servlet 的底层编程模型的知识会有所帮助,JAX-WS 等都是基于该模型构建的。这个answer很好地解释了事情。

    要在session 期间保留与客户端相关的信息,您可以在方法主体中获取会话并将信息存储在其中:

    Message message = PhaseInterceptorChain.getCurrentMessage();
    HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
    HttpSession  session = request.getSession(true);
    session.setAttribute("id", id);
    

    在随后的方法调用中,您可以以相同的方式检索会话数据。

    一个非常基础的(古老的)教程:Maintaining Client State。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-25
      • 2011-01-17
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2021-03-24
      相关资源
      最近更新 更多