Mongo无法在Spring 4 Java API中打开连接

时间:2018-08-02 20:23:24

标签: java spring mongodb spring-mvc

我有一个我们使用Spring 4和Mongo数据库编写的API。当应用程序加载到本地WAS中时,我可以看到该应用程序将退出并连接到数据库。但是,当我执行应该打开查询的函数时,出现套接字关闭错误。

我的配置:

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    logger.info("loading MongoDBFactory bean" );
    String PROCESS_ID_MONGO_KEY = "PROCESS_ID_MONGO";

    Credentials credentials = credentialsManager().getCredentialsFor(PROCESS_ID_MONGO_KEY);

    MongoClient mongoClient = new MongoClient(
            Arrays.asList(new ServerAddress(PropertiesManagerUtility.getKeyValue(CollectionType.CREDENTIAL, "mongo.url"), 27017)),
            Arrays.asList(MongoCredential.createPlainCredential(credentials.getUserid(), "$external", credentials.getPassword().toCharArray())),
            MongoClientOptions.builder()
                    .sslEnabled(true).connectTimeout(30)
                    .writeConcern(WriteConcern.MAJORITY)
                    .socketKeepAlive(true)
                    .build());
    return new SimpleMongoDbFactory(mongoClient, PropertiesManagerUtility.getKeyValue(CollectionType.CREDENTIAL, "mongo.db"));
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
    logger.info("loading MongoTemplate bean" );
   // MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    return new MongoTemplate(mongoDbFactory());
}

我的道

@Component("achResponseDMDao")
public class AchResponseDMDaoImpl implements IBasicDao<AchResponseDM>{
    @Autowired
    MongoTemplate mongoTemplate;

public AchResponseDMDaoImpl(MongoTemplate mongoTemplate){
    this.mongoTemplate = mongoTemplate;
}

@Override
public AchResponseDM findByResponseCode( String responseCode){
    Query query = new Query(Criteria.where("responseCode").is(responseCode));        
    return mongoTemplate.findOne(query, AchResponseDM.class);
}
...
}

问题是我认为Spring会使用MongoFactory给我一个新的连接,但是看来原始连接已关闭并且不再创建任何连接。我需要做什么?预先感谢。

1 个答案:

答案 0 :(得分:0)

注入工厂而不是MongoTemplate实例会根据需要创建新的连接。相应的DAOImpl将具有@Autowired MongoFactory mongoFactory;,并且该方法将创建new mongoTemplate(mongoFactory).find(...)或其他实例。

生成的DAO如下:

@Component("achResponseDMDao")
public class AchResponseDMDaoImpl implements IBasicDao<AchResponseDM>{
    @Autowired
    MongoFactory mongoFactory;

@Override
public AchResponseDM findByResponseCode( String responseCode){
    Query query = new Query(Criteria.where("responseCode").is(responseCode));        
    List<AchResponseDM> listOfResponses = mongoTemplate(mongoFactory).find(query, AchResponseDM.class);
    return (listOfResponses!=null && !listOfResponses.isEmpty())?listOfResponses.get(0):defaultNonNullResponse();
}
...
}