簡體   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