繁体   English   中英

如何在 Spring Boot 中初始化一次 MongoClient 并使用它的方法?

[英]How to initialize MongoClient once in Spring Boot and use its methods?

您好,我正在尝试在 Spring 引导中成功连接后导出MongoClient ,并且我正在尝试在其他文件中使用它,这样我就不必每次需要在 MongoDB 数据库中进行更改时都调用连接。

连接非常简单,但目标是将应用程序连接到我的数据库一次,然后通过在任何 Java 文件中导入它来在我想要的任何地方使用它。

谢谢

以下是创建MongoClient实例、在 Spring 引导应用程序中配置和使用它的几种方法。

(1) 使用基于 Java 的元数据注册 Mongo 实例:

@Configuration
public class AppConfig {
    public @Bean MongoClient mongoClient() {
        return MongoClients.create();
    }
}

CommandLineRunnerrun方法的用法(所有示例都类似地运行):

@Autowired 
MongoClient mongoClient;

// Retrieves a document from the "test1" collection and "test" database.
// Note the MongoDB Java Driver API methods are used here.
private void getDocument() {
    MongoDatabase database = client.getDatabase("test");
    MongoCollection<Document> collection = database.getCollection("test1");
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
}


(2) 使用 AbstractMongoClientConfiguration class 配置并与 MongoOperations 一起使用:

@Configuration
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create();
    }

    @Override
    protected String getDatabaseName() {
        return "newDB";
    }
}

请注意,您可以设置可以连接的数据库名称 ( newDB )。 此配置用于使用 MongoDB 数据库使用 Spring 数据 MongoDB API: MongoOperations (及其实现MongoTemplate )和MongoRepository

@Autowired 
MongoOperations mongoOps;

// Connects to "newDB" database, and gets a count of all documents in the "test2" collection.
// Uses the MongoOperations interface methods.
private void getCollectionSize() {
    Query query = new Query();
    long n = mongoOps.count(query, "test2");
    System.out.println("Collection size: " + n);
}


(3) 使用 AbstractMongoClientConfiguration class 配置并与 MongoRepository 一起使用

使用相同的配置MongoClientConfiguration class(在主题 2 中),但另外使用@EnableMongoRepositories进行注释。 在这种情况下,我们将使用MongoRepository接口方法以 Java 对象的形式获取集合数据。

存储库:

@Repository
public interface MyRepository extends MongoRepository<Test3, String> {

}

Test3.java POJO class 代表test3集合的文档:

public class Test3 {

    private String id;
    private String fld;

    public Test3() {    
    }

    // Getter and setter methods for the two fields
    // Override 'toString' method
    ...
}

以下方法获取文档并打印为 Java 对象:

@Autowired 
MyRepository repository;

// Method to get all the `test3` collection documents as Java objects.
private void getCollectionObjects() {
    List<Test3> list = repository.findAll();
    list.forEach(System.out::println);
}
    **Pom Changes :**
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
    
            <!-- jpa, crud repository -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
    **Main Application :**
    
    @SpringBootApplication(exclude = {
            MongoAutoConfiguration.class,
            MongoDataAutoConfiguration.class
    })
    public class Application {
    public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
**MongoConfig Class :**

@Configuration
@EnableMongoRepositories({"com.repository.mongo"})
public class MongoConfig {

    private final MongoProperties properties;

    public MongoConfig(MongoProperties properties) {
        this.properties = properties;
    }

    @Bean
    public MongoClient mongo() throws IOException {
        log.info("Creating mongo client. Socket timeout: {}, request timeout: {}",
                properties.getSocketTimeout(), properties.getConnectTimeout()
        );
        MongoCredential credential = MongoCredential.createCredential(properties.getUsername(), properties.getDatabase(), readPassword(properties.getPasswordFilePath()).toCharArray());

        MongoClientSettings settings = MongoClientSettings.builder()
                .credential(credential)
                .applyToSocketSettings(builder -> builder.readTimeout(properties.getSocketTimeout().intValue(), TimeUnit.MILLISECONDS).connectTimeout(properties.getConnectTimeout().intValue(), TimeUnit.MILLISECONDS))
                .applyToClusterSettings(builder ->
                        builder.hosts(Arrays.asList(new ServerAddress(properties.getHost(), properties.getPort()))).requiredReplicaSetName(properties.getReplicaSet()))
                .build();

        return MongoClients.create(settings);
    }


    @Bean
    public MongoDatabase database() throws IOException {
        // Allow POJOs to be (de)serialized
        CodecRegistry extendedRegistry = fromRegistries(
                MongoClientSettings.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build())
        );
        return mongo().getDatabase(properties.getDatabase()).withCodecRegistry(extendedRegistry);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws IOException {
        return new MongoTemplate(mongo(), properties.getDatabase());
    }

    @PreDestroy
    public void destroy() throws IOException {
        mongo().close();
    }

    private String readPassword(String path) throws IOException {
       // return Files.readString(Paths.get(path));
        return "****";
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM