簡體   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