如何在Sping Boot 中启动MongoDB更改流?

j9per5c4  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(127)

因此,我在Sping Boot 应用程序中构建了一个非常基本的MongoDB更改流:

public class MongoDBChangeStream {

    public void changeStream() {

        // connect to the local database server
        MongoClient mongoClient = MongoClients.create("db uri goes here");

        // Select the MongoDB database
        MongoDatabase database = mongoClient.getDatabase("MyDatabase");

        // Select the collection to query
        MongoCollection<Document> collection = database.getCollection("teams");

        // Create pipeline for operationType filter
        List<Bson> pipeline = Arrays.asList(
                Aggregates.match(
                        Filters.in(
                                "operationType",
                                Arrays.asList("insert", "update", "delete")
                        )));

        // Create the Change Stream
        ChangeStreamIterable<Document> changeStream = collection.watch(pipeline)
                .fullDocument(FullDocument.UPDATE_LOOKUP);

        // Iterate over the Change Stream
        for (ChangeStreamDocument<Document> changeEvent : changeStream) {
            // Process the change event here
            switch (changeEvent.getOperationType()) {
                case INSERT:
                    System.out.println("MongoDB Change Stream detected an insert");
                    break;
                case UPDATE:
                    System.out.println("MongoDB Change Stream detected an update");
                    break;
                case DELETE:
                    System.out.println("MongoDB Change Stream detected a delete");
                    break;
            }
        }
    }
}

正如您所看到的,我正在监听***'teams'集合中的***insertupdates***和***deletes,然后在控制台中打印出相应的消息。
但是实际上我如何启动侦听器呢?当我运行应用程序时,需要启动changeStream,以便它开始监视集合..我如何做到这一点呢?

qzwqbdag

qzwqbdag1#

如果我理解正确的话,您可以简单地添加一个带有@PostConstruct方法的@Configuration类:

@Configuration
public class DatabaseChangeStreamInitialiser {

    @PostConstruct
    public void init() {
      // eg, call `MongoDBChangeStream.changeStream`
    }
}

@Component
public class DatabaseChangeStreamInitialiser {

    @EventListener(ContextRefreshedEvent.class)
    public void init() {
      // eg, call `MongoDBChangeStream.changeStream`
    }
}

有很多方法可以做到这一点,你可以用@EventListener注解来监听ContextRefreshedEvent.创建InitializingBean,或者甚至只是在你的类中找到main方法用@SpringBootApplication注解。
此处记录了一些其他选项:Execute method on startup in Spring
如果不是的话,如果你能描述一下你的spring-boot应用程序的确切启动过程和细节,那会很有帮助。

相关问题