使用 Java 和 JBoss 进行长轮询 [英] Long Polling with Java and JBoss

查看:39
本文介绍了使用 Java 和 JBoss 进行长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个例子,如何在java中实现longpoling机制.我喜欢使用无状态 EJB.

I'm looking for an example, how to implement a longpoling mechanism in java. I would love to use a stateless EJB.

我知道这样的事情会奏效:

I know that something like that would work:

@WebService(serviceName="mywebservice")
@Stateless
public class MyWebService {
    @WebMethod
    public String longPoll() {
         short ct = 0;
         while(someCondition == false && ct < 60) {
             sleep(1000);  // 1 sec
             ct++;
         }
         if (someCondition)
             return "got value";
         else
             return "";
    }
}

不幸的是,我知道这不能扩展.我可以在没有完成响应的情况下返回 webmethod 并在其他地方完成它吗?

Unfortunately i know that this does'nt scale. Can i return in the webmethod without finishing the response and finish it somewhere else?

推荐答案

您尝试实现的东西称为服务器推送.每个网络服务器/应用程序服务器都有一个线程池,比如 10 个用于处理网络请求的线程,如果所有这些线程都进入睡眠"状态,那么在这些睡眠"之一存在之前,不会为其他网络请求提供服务.一些解决方案是增加这些线程的数量,但是你会吃掉更多的内存和更多的操作系统资源(每个线程的成本).所以,是的,您的服务器推送"实施不可扩展.

The thing you're trying to implement is called server push. Each webserver/appserver has a pool of threads, say 10 threads for processing web requests, if all those threads will go into 'sleep' no other web request will be serviced until one of those 'sleeps' exists. Some solution is to increase number of those threads but then you'll eat more memory and more operating system resources (each thread costs). So yes, your implementation of 'server push' isn't scalable.

解决方案:

  • 您的 Web 应用程序可以每(例如)5 秒发送一次 http 请求,以检查您的someCondition"是否已更改,然后获取数据
  • AFAIK、Tomcat(也包括 JBoss)已经有一些连接器"来支持此类请求,因此不需要 Thread.sleep() 或信号量
  • 使用最新的 Web 服务器实现 Servlet API 3,它还支持这种长时间运行的 HTTP 请求
  • 阅读更多:实现 Comet 的在线教程(服务器推送)

这篇关于使用 Java 和 JBoss 进行长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆