【问题标题】:Container managed MongoDB Connection in Liberty + Spring DataLiberty + Spring Data 中的容器管理 MongoDB 连接
【发布时间】:2019-01-21 02:05:21
【问题描述】:
我们在Spring Boot + spring data (后端) + MongoDB 中开发了一个应用程序,并使用IBM Websphere Liberty 作为应用程序服务器。我们在yml 文件中使用了“Application Managed DB Connection”,并享受了Spring Boot autoconfiguration 的好处。
由于政策变更,我们需要在 Liberty Server(使用 mongo 功能)中管理我们的数据库连接,位于 Server.xml。我花了一整天的时间来寻找一个很好的例子来做到这一点,但在 Spring 中没有找到任何示例,在 IBM Websphere Liberty Server 中使用 "Container Managed MongoDB Connection"。
有人可以在这里支持吗?
【问题讨论】:
标签:
mongodb
spring-boot
spring-data
websphere-liberty
open-liberty
【解决方案1】:
过去,Liberty 为 server.xml 提供了一个专用的 mongodb-2.0 功能,但是此功能提供的好处很少,因为您仍然需要带上自己的 MongoDB 库。此外,随着时间的推移,MongoDB 对其 API 进行了重大的重大更改,包括 MongoDB 的配置方式。
由于 MongoDB API 在不同版本之间发生了如此巨大的变化,我们发现最好不在 Liberty 中提供任何新的 MongoDB 功能,而是建议用户像这样简单地使用 CDI 生成器:
CDI 生产者(也拥有任何配置):
@ApplicationScoped
public class MongoProducer {
@Produces
public MongoClient createMongo() {
return new MongoClient(new ServerAddress(), new MongoClientOptions.Builder().build());
}
@Produces
public MongoDatabase createDB(MongoClient client) {
return client.getDatabase("testdb");
}
public void close(@Disposes MongoClient toClose) {
toClose.close();
}
}
使用示例:
@Inject
MongoDatabase db;
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
public void add(CrewMember crewMember) {
MongoCollection<Document> crew = db.getCollection("Crew");
Document newCrewMember = new Document();
newCrewMember.put("Name",crewMember.getName());
newCrewMember.put("Rank",crewMember.getRank());
newCrewMember.put("CrewID",crewMember.getCrewID());
crew.insertOne(newCrewMember);
}
这只是基础知识,但以下博客文章将更详细地介绍代码示例:
https://openliberty.io/blog/2019/02/19/mongodb-with-open-liberty.html
【解决方案2】:
查看this other stackoverflow solution。以下是您如何在 Spring Boot 应用程序中使用它的扩展。
您应该能够以相同的方式注入数据源。您甚至可以将其注入到您的配置中并将其包装在 Spring DelegatingDataSource 中。
@Configuration
public class DataSourceConfiguration {
// This is the last code section from that link above
@Resource(lookup = "jdbc/oracle")
DataSource ds;
@Bean
public DataSource mySpringManagedDS() {
return new DelegatingDataSource(ds);
}
}
那么你应该可以将mySpringManagedDSDataSource注入你的Component、Service等。