在与MongoDB数据库建立连接的方法中使用Dropwizard配置

时间:2017-07-06 15:57:02

标签: java mongodb dropwizard mongodb-java

我正在编写Dropwizard微服务,用于获取MongoDB数据库中的数据。微服务工作正常,但我很难在我的DAO中使用来自我的Dropwizard配置Java类的配置。目前我有

public class XDAO implements IXDAO {

    protected DB db;
    protected DBCollection collection;

    /* singleton */
    private static XDAO instance;

    /* Get singleton */
    public static synchronized XDAO getSingleton(){
       if (instance == null){
         instance = new XDAO();
       }       
      return instance;
    }

    /* constructor */
    public XDAO(){
       initDatabase();
       initDatabaseIndexes();
    }

    private void initDatabase(){
       MongoClient client = null;

       try {
           client = new Mongo("10.126.80.192",27017); 
           db = client.getDB("terre");
           //then some other code
       }

       catch (final MongoException e){
         ...
       }

       catch (UnknownHostException e){
         ...
       }

     }

 }

我想在这两行中解密三个参数:

  client = new Mongo("10.126.80.192", 27017); 
  db = client.getDB("terre");

我的MongoConfiguration Java类是:

public class MongoConfiguration extends Configuration {

@JsonProperty
@NotEmpty
public String host;

@JsonProperty
public int port = 27017;

@JsonProperty
@NotEmpty
public String db_name;

public String getMongohost() {
    return host;
}

public void setMongohost(String host) {
    this.host = host;
}

public int getMongoport() {
    return port;
}

public void setMongoport(int port) {
    this.port = port;
}

public String getDb_name() {
    return db_name;
}

public void setDb_name(String db_name) {
    this.db_name = db_name;
}

}

使用DAO的My Resource类是:

@Path("/mongo")
@Produces(MediaType.APPLICATION_JSON)
public class MyResource {

private XDAO xDAO = XDAO.getSingleton();

private String mongohost;
private String db_name;
private int mongoport;

public MyResource(String db_name, String mongohost, int mongoport) {
    this.db_name = db_name;
    this.mongohost = mongohost;
    this.mongoport = mongoport;
}

public MyResource() {
}

@GET
@Path("/findByUUID")
@Produces(value = MediaType.APPLICATION_JSON)
@Timed
public Entity findByUUID(@QueryParam("uuid") String uuid) {

    return xDAO.findByUUid(uuid);
  }
}

在我的应用程序类中有

  @Override
  public void run(final MongoConfiguration configuration, final Environment environment) {

    final MyResource resource = new MyResource(configuration.getDb_name(), configuration.getMongohost(), configuration.getMongoport());
    environment.jersey().register(resource);
   }

为了解决我的问题,我尝试了很多东西。我尝试的最后一件事是在我的XDAO中添加这四个字段

  private String mongohost;
  private String db_name;
  private int mongoport;
  private static final MongoConfiguration configuration = new MongoConfiguration();

在XDAO的构造函数中使用这段代码:

public XDAO(){
    instance.mongohost = configuration.getMongohost();
    instance.mongoport = configuration.getMongoport();
    instance.db_name = configuration.getDb_name();
    /* then like before */
    initDatabase();
    initDatabaseIndexes();
}

当我尝试这个时,我的initDatabase方法被调用时有一个空指针异常:mongoHost和db_name为null

2 个答案:

答案 0 :(得分:0)

问题是您使用private static final MongoConfiguration configuration = new MongoConfiguration();在XDAO中创建配置,而不是使用Dropwizard的run方法中的配置。

执行此操作时, new 配置中的字段hostdb_name为空,这就是您在实例化XDAO时获取NPE的原因

您需要将应用程序类中从Dropwizard获得的MongoConfiguration实例传递给XDAO,理想情况是创建单例XDAO时它具有非空值db_namehost

此代码下面是问题的一部分 - 您正在创建单例而不给XDAO MongoConfiguration配置实例public class XDAO implements IXDAO { //... snip /* Get singleton */ public static synchronized XDAO getSingleton(){ if (instance == null){ instance = new XDAO(); // no configuration information is included! } return instance; } /* constructor */ public XDAO(){ initDatabase(); // this call needs db_name & host but you haven't set those yet!! initDatabaseIndexes(); }

@Override
public void run(final MongoConfiguration configuration, final Environment environment) {

  XDAO XDAOsingleton = new XDAO(configuration);
  XDAO.setSingletonInstance(XDAOsingleton); // You need to create this static method.

  final MyResource resource = new MyResource(configuration.getDb_name(), configuration.getMongohost(), configuration.getMongoport()); // MyResource depends on XDAO so must be created after XAO's singleton is set
  environment.jersey().register(resource);
}

我建议你修改你的应用程序类,按照以下方式创建XDAO:

initDatabase()

您可能还需要从XDAO的构造函数中取出public static synchronized XDAO getSingleton()等,具体取决于您是否保留MyResource

我还建议您将public MyResource(XDAO xdao)的构造函数更改为<table border='1' cellpadding='25'> <th>Status</th> <tr><td><select><option value="">Open</option><option value="">Closed</option></select></td></tr><br> <tr><td><select><option value="">Open</option><option value="">Closed</option></select></td></tr><br> <tr><td><select><option value="">Open</option><option value="">Closed</option></select></td></tr><br> </table>。资源类似乎不需要配置信息,最好是明确依赖XDAO(然后你也不需要将XDAO单例保留在XDAO内部的静态字段中&#39 ; s班)。

答案 1 :(得分:0)

要以简单的Dropwizard方式集成MongoDB,请尝试使用 MongoDB托管对象。我将通过3个简单步骤解释这一点:

第1步:创建一个简单的MongoManged类:

mongoHost : localhost
mongoPort : 27017
mongoDB : softwaredevelopercentral

步骤2:在配置yml文件中提及MongoDB主机,端口,数据库名称:

public class DropwizardMongoDBApplication extends Application<DropwizardMongoDBConfiguration> {

private static final Logger logger = LoggerFactory.getLogger(DropwizardMongoDBApplication.class);

public static void main(String[] args) throws Exception {
    new DropwizardMongoDBApplication().run("server", args[0]);
}

@Override
public void initialize(Bootstrap<DropwizardMongoDBConfiguration> b) {
}

@Override
public void run(DropwizardMongoDBConfiguration config, Environment env)
        throws Exception {
    MongoClient mongoClient = new MongoClient(config.getMongoHost(), config.getMongoPort());
    MongoManaged mongoManaged = new MongoManaged(mongoClient);
    env.lifecycle().manage(mongoManaged);
    MongoDatabase db = mongoClient.getDatabase(config.getMongoDB());
    MongoCollection<Document> collection = db.getCollection(config.getCollectionName());
    logger.info("Registering RESTful API resources");
    env.jersey().register(new PingResource());
    env.jersey().register(new EmployeeResource(collection, new MongoService()));
    env.healthChecks().register("DropwizardMongoDBHealthCheck",
            new DropwizardMongoDBHealthCheckResource(mongoClient));
}
}

步骤3:在Application Class中将所有内容绑定在一起:

<a href="#" class="LoadBtn">Load Gallery Plugin</a>
<div id="PhotoGrid">Plugin shortcode should be loaded here</div>

我已经使用了这些步骤并编写了博客文章,并在GitHub上提供了一个示例工作应用程序代码。请检查:http://softwaredevelopercentral.blogspot.com/2017/09/dropwizard-mongodb-tutorial.html