Liberty + Spring Data中的容器管理MongoDB连接

问题描述 投票:2回答:2

我们在Spring Boot + spring data(后端)+ MongoDB开发了一个应用程序,并使用IBM Websphere Liberty作为应用程序服务器。我们在yml文件中使用了“Application Managed DB Connection”并享受了Spring Boot autoconfiguration的好处。

由于策略更改,我们需要在Server.xml中管理Liberty Server中的数据库连接(使用mongo功能)。我花了一整天时间找到一个很好的例子,但是在IBM Websphere Liberty Server中没有找到Spring中的“Container Managed MongoDB Connection”。

有人可以支持吗?

mongodb spring-boot spring-data websphere-liberty open-liberty
2个回答
0
投票

看看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);
    }

}

然后你应该能够将mySpringManagedDS DataSource注入你的ComponentService等。


0
投票

在过去,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

© www.soinside.com 2019 - 2024. All rights reserved.