Live reload on Database update

Viewed 963

Previously I worked on Meteor and MongoDB. when I was working on it I noticed that Meteor server reloads the data if any changes happen in Mongo DB.

Can we do these things in Spring Boot, Java? I checked Live reload tools and plugins. These plugins and tools reload or restart the server when code changes, but not when DB is changed.

1 Answers

I assume that you are talking about MongoDB change streams.

Yes you can register a listener:

Imperative Style

Change stream events can be consumed using a MessageListener registered within a MessageListenerContainer. The container takes care of running the task in a separate Thread pushing events to the MessageListener.

@Configuration
class Config {

    @Bean
    MessageListenerContainer messageListenerContainer(MongoTemplate template) {
        return new DefaultMessageListenerContainer(template);
    }
}

Once the MessageListenerContainer is in place MessageListeners can be registered.

MessageListener<ChangeStreamDocument<Document>, Person> messageListener = (message) -> {
    System.out.println("Hello " + message.getBody().getFirstname());
};

ChangeStreamRequest<Person> request = ChangeStreamRequest.builder()
    .collection("person")
    .filter(newAggregation(match(where("operationType").is("insert"))))
    .publishTo(messageListener)
    .build();

Subscription subscription = messageListenerContainer.register(request, Person.class);

// ...

Reactive Style

Change stream events be directly consumed via a Flux connected to the change stream.

Flux changeStream = reactiveTemplate
    .changeStream(newAggregation(match(where("operationType").is("insert"))),
                Person.class, ChangeStreamOptions.empty(), "person");

changeStream.doOnNext(event -> System.out.println("Hello " + event.getBody().getFirstname()))
    .subscribe();

Read more about that: https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/change-streams

Related