-->

Quarkus mongodb integration

2019-08-17 15:52发布

问题:

I'm using quarkus to build an application that needs to connect to MongoDB.

However going over the documentation I could not find any module or guide that show me how can I do it:

https://quarkus.io/

There is a guide about hibernate and JPA, but nothing about mongodb.

Does anyone manage to do it? Can you share with me a repository with an example?

回答1:

I have use the following to access mongodb databases in some quarkus demo code:

@ApplicationScoped
public class MongoClientFactory {

    @Inject
    private Logger logger;

    @Inject
    @ConfigProperty(name="mongo.user")
    private String mongoUser;

    @Inject
    @ConfigProperty(name="mongo.password")
    private String mongoPassword;

    @Inject
    @ConfigProperty(name="mongo.host")
    private String mongoHost;

    @Inject
    @ConfigProperty(name="mongo.port", defaultValue="27017")
    private int mongoPort;

    @Inject
    @ConfigProperty(defaultValue="admin")
    private String mongoAdminDb;

    private MongoClient mongoClient;
    private ServerAddress serverAddress;
    private MongoCredential mongoCredential;

    @PostConstruct
    void buildMongoClient() {
        logger.info("Building MongoClientFactory");
        serverAddress = new ServerAddress(mongoHost, mongoPort);
        mongoCredential = MongoCredential.createCredential(mongoUser, mongoAdminDb, mongoPassword.toCharArray());
    }

    @Produces
    public MongoClient produceMongoClient() {
        if (mongoClient == null) {
            mongoClient = new MongoClient(serverAddress, mongoCredential, MongoClientOptions.builder().build());
            logger.info("Connected to MongoDB server on {}:{}", mongoHost, mongoPort);
        }
        return mongoClient;
    }

    @PreDestroy
    void cleanup() {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }

}

Then I can just inject the client where ever needed:

public class SomBusinessObject {

    @Inject
    private MongoClient mongoClient;


    ...
}

The Mongo driver is added to the pom too:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.8.2</version>
</dependency>

I have not yet tested this with a native build. The standalone jar seems to run fine though.

Update

GraalVM Version 1.0.0-rc15 CE does not like the mongo driver. It seems to be impacted by Error: No instances are allowed in the image heap for a class that is initialized or reinitialzied at image runtime: sun.security.provider.NativePRNG #712.

Additionally, the Quarkus dependency analyser appears to be sucking in optional dependencies, such as com.github.jnr:jnr-unixsocket and org.xerial.snappy:snappy-java.



回答2:

Latest versions of Quarkus have added MongoDB support.

https://quarkus.io/guides/mongo-guide