在Dropwizard中注册资源

5

我无法在Dropwizard应用程序的run()方法中注册多个资源。当我这样做时,我会得到以下异常:

Exception in thread "main" MultiException[java.lang.IllegalArgumentException: A metric named io.dropwizard.db.ManagedPooledDataSource.postgresql.active already exists, java.util.concurrent.RejectedExecutionException: org.eclipse.jetty.util.thread.NonBlockingThread@27f74733]
at org.eclipse.jetty.server.Server.doStart(Server.java:329)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at io.dropwizard.cli.ServerCommand.run(ServerCommand.java:43)
at io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:43)
at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:76)
at io.dropwizard.cli.Cli.run(Cli.java:70)
at io.dropwizard.Application.run(Application.java:73)
at com.xxx.xxx.yyy.GobblerHTTPApplication.main(GobblerHTTPApplication.java:19)

2
你能添加你的代码吗? - Manikandan
还有一些细节信息,比如您使用的Dropwizard版本可能会很有用。 - Edd
2个回答

6

如果您使用Hibernate初始化数据库,例如在主应用程序中使用以下代码(两次):

private final HibernateBundle<Cfg> hib1 = new HibernateBundle<Cfg>(ImmutableList.of(SomeHibernateModel.class), new SessionFactoryFactory()) {
    @Override
    public DataSourceFactory getDataSourceFactory(Cfg configuration) {
        return configuration.getDatabaseFactory();
    }
};

如果需要,可以覆盖另一个方法:´name()´方法。该方法提供了您的指标名称的最后一部分(´.postgresql.active´部分)例如:

private final HibernateBundle<Cfg> hib1 = new HibernateBundle<Cfg>(ImmutableList.of(SomeHibernateModel.class), new SessionFactoryFactory()) {
    @Override
    public DataSourceFactory getDataSourceFactory(Cfg configuration) {
        return configuration.getDatabaseFactory();
    }
    @Override
    protected String name() {
        return "hibernate.accesslog";
    }

};

这种方法对我非常有效,谢谢你的提示。 - stve
1
@stve 注意,如果你打算使用@UnitOfWork,那么你只能为其中一个获取到会话。这个问题已经在https://github.com/dropwizard/dropwizard/issues/1217中被提出,并且在几天前已经合并。所以它可能还没有在你的版本中得到修复。 - helt
感谢您指出那个问题。正如您所指出的,我在使用@UnitOfWork时遇到了一些问题。幸运的是,看起来0.9.0版本很快就会发布。 - stve

5

看起来你正在为每个资源初始化两次Postgres实例,这是不必要的。你可以简单地先初始化所有的存储等,然后注册你的资源。做法如下:

    /* Service manager */
    environment.lifecycle().manage(new XYZServiceManager());

    /* Adding Resources */
    environment.jersey().register(new FirstResource());
    environment.jersey().register(new SecondResource());

希望这能解决你的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接