繁体   English   中英

在dropwizard中使用Cometd

[英]Using cometd in dropwizard

我正在尝试使用cometd作为dropwizard的servlet,但是BayeuxServer似乎没有注入我的服务中。 我正在这样添加我的两个servlet(请注意,我没有使用web.xml所以我自己定义了参数):

cometdConfig.put("services", MyService.class.getCanonicalName());

System.out.print("OrderService name: " + MyService.class.getCanonicalName());

environment.addServlet(AnnotationCometdServlet.class, "/cometd/*").addInitParams(cometdConfig).setInitOrder(1);
environment.addServlet(new MyServiceServlet(), "/orders/*").setInitOrder(2);

和我的服务(这是我的代码失败的地方):

public class MyService
implements MyWatcher.Listener
{
   @Inject
   private BayeuxServer bayeuxServer;
   @Session
   private LocalSession sender;

   private final String _channelName;

   private ServerChannel _channel = null;

   public OrderService() {
      _channelName = "/cometd/";
      initChannel();
   }

   private void initChannel() {
      // I get an NPE here
      bayeuxServer.createIfAbsent(_channelName, new ConfigurableServerChannel.Initializer() {
        @Override
        public void configureChannel(ConfigurableServerChannel channel) {
           // ...
        }
      });
    _channel = bayeuxServer.getChannel(_channelName);
   }
}

我也尝试过创建自己的BayeuxServer实例,但是随后在BayeuxServerImpl.freeze();中导致了一个单独的NPE BayeuxServerImpl.freeze();

任何人都知道如何与dropwizard一起正确使用Cometd吗?

为了注入BayeuxServer实例,CometD必须具有要注入的服务的实例,在这种情况下,是类MyService的实例。

不幸的是,从构造函数(我认为您在上面将其命名为OrderService )中,您正在调用initChannel()方法,该方法尝试使用由于构造函数仍在执行而尚未注入的BayeuxServer字段。

解决方案是将您的频道初始化推迟到使用@PostConstruct注释的其他方法:

public class MyService
{
    @Inject
    private BayeuxServer bayeuxServer;
    @Session
    private LocalSession sender;
    private final String _channelName;
    private ServerChannel _channel;

    public MyService() 
    {
        _channelName = "/cometd/";
    }

    @PostConstruct
    private void initChannel() 
    {
        _channel = bayeuxServer.createChannelIfAbsent(_channelName).getReference();
    }
}

使用的CometD API来自CometD 2.7.0,如果您使用的是较旧的CometD版本,则建议使用它。

暂无
暂无

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

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