#215 - Add reactive examples for MongoDB, Apache Cassandra and Redis.

This commit is contained in:
Mark Paluch
2016-10-28 17:46:19 +02:00
committed by Oliver Gierke
parent cf5d9f3562
commit 20879e7fa3
29 changed files with 1855 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
/**
* Simple configuration that registers a {@link LoggingEventListener} to demonstrate mapping behavior when streaming
* data.
*
* @author Mark Paluch
*/
@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@EnableReactiveMongoRepositories
@AutoConfigureAfter(EmbeddedMongoAutoConfiguration.class)
class ApplicationConfiguration extends AbstractReactiveMongoConfiguration {
@Bean
public LoggingEventListener mongoEventListener() {
return new LoggingEventListener();
}
@Override
@Bean
public MongoClient mongoClient() {
return MongoClients.create();
}
@Override
protected String getDatabaseName() {
return "reactive";
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* An entity to represent a Person.
*
* @author Mark Paluch
*/
@Data
@RequiredArgsConstructor
@Document
public class Person {
private @Id String id;
private final String firstname;
private final String lastname;
private final int age;
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.data.mongodb.repository.InfiniteStream;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
/**
* Repository interface to manage {@link Person} instances.
*
* @author Mark Paluch
*/
public interface ReactivePersonRepository extends ReactiveCrudRepository<Person, String> {
/**
* Derived query selecting by {@code lastname}.
*
* @param lastname
* @return
*/
Flux<Person> findByLastname(String lastname);
/**
* String query selecting one entity.
*
* @param lastname
* @return
*/
@Query("{ 'firstname': ?0, 'lastname': ?1}")
Mono<Person> findByFirstnameAndLastname(String firstname, String lastname);
/**
* Derived query selecting by {@code lastname}. {@code lastname} uses deferred resolution that does not require
* blocking to obtain the parameter value.
*
* @param lastname
* @return
*/
Flux<Person> findByLastname(Mono<String> lastname);
/**
* Derived query selecting by {@code firstname} and {@code lastname}. {@code firstname} uses deferred resolution that
* does not require blocking to obtain the parameter value.
*
* @param firstname
* @param lastname
* @return
*/
Mono<Person> findByFirstnameAndLastname(Mono<String> firstname, String lastname);
/**
* Use a tailable cursor to emit a stream of entities as new entities are written to the capped collection.
*
* @return
*/
@InfiniteStream
Flux<Person> findWithTailableCursorBy();
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import rx.Observable;
import rx.Single;
import org.springframework.data.mongodb.repository.InfiniteStream;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.reactive.RxJava1CrudRepository;
/**
* Repository interface to manage {@link Person} instances.
*
* @author Mark Paluch
*/
public interface RxJava1PersonRepository extends RxJava1CrudRepository<Person, String> {
/**
* Derived query selecting by {@code lastname}.
*
* @param lastname
* @return
*/
Observable<Person> findByLastname(String lastname);
/**
* String query selecting one entity.
*
* @param lastname
* @return
*/
@Query("{ 'firstname': ?0, 'lastname': ?1}")
Single<Person> findByFirstnameAndLastname(String firstname, String lastname);
/**
* Derived query selecting by {@code lastname}. {@code lastname} uses deferred resolution that does not require
* blocking to obtain the parameter value.
*
* @param lastname
* @return
*/
Observable<Person> findByLastname(Single<String> lastname);
/**
* Derived query selecting by {@code firstname} and {@code lastname}. {@code firstname} uses deferred resolution which
* does not require blocking to obtain the parameter value.
*
* @param firstname
* @param lastname
* @return
*/
Single<Person> findByFirstnameAndLastname(Single<String> firstname, String lastname);
/**
* Use a tailable cursor to emit a stream of entities as new entities are written to the capped collection.
*
* @return
*/
@InfiniteStream
Observable<Person> findWithTailableCursorBy();
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import static org.assertj.core.api.Assertions.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.RxReactiveStreams;
import java.util.concurrent.CountDownLatch;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link ReactiveMongoTemplate}.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactiveMongoTemplateIntegrationTest {
@Autowired ReactiveMongoTemplate template;
@Before
public void setUp() {
template.collectionExists(Person.class) //
.flatMap(exists -> exists ? template.dropCollection(Person.class) : Mono.just(exists)) //
.flatMap(exists -> template.createCollection(Person.class)) //
.then() //
.block();
template
.insertAll(Flux.just(new Person("Walter", "White", 50), //
new Person("Skyler", "White", 45), //
new Person("Saul", "Goodman", 42), //
new Person("Jesse", "Pinkman", 27)).collectList())
.then() //
.block();
}
/**
* This sample performs a count, inserts data and performs a count again using reactive operator chaining. It prints
* the two counts ({@code 4} and {@code 6}) to the console.
*/
@Test
public void shouldInsertAndCountData() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
template.count(new Query(), Person.class) //
.doOnNext(System.out::println) //
.thenMany(template.save(Flux.just(new Person("Hank", "Schrader", 43), //
new Person("Mike", "Ehrmantraut", 62)))) //
.last() //
.flatMap(v -> template.count(new Query(), Person.class)) //
.doOnNext(System.out::println) //
.doOnComplete(countDownLatch::countDown) //
.doOnError(throwable -> countDownLatch.countDown()) //
.subscribe();
countDownLatch.await();
}
/**
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void convertReactorTypesToRxJava1() throws Exception {
Flux<Person> flux = template.find(Query.query(Criteria.where("lastname").is("White")), Person.class);
long count = RxReactiveStreams.toObservable(flux).count().toSingle().toBlocking().value();
assertThat(count).isEqualTo(2);
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import static org.assertj.core.api.Assertions.*;
import reactor.core.Cancellation;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link ReactivePersonRepository} using Project Reactor types and operators.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReactivePersonRepositoryIntegrationTest {
@Autowired ReactivePersonRepository repository;
@Autowired ReactiveMongoOperations operations;
@Before
public void setUp() {
operations.collectionExists(Person.class) //
.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
.flatMap(o -> operations.createCollection(Person.class, new CollectionOptions(1024 * 1024, 100, true))) //
.then() //
.block();
repository
.save(Flux.just(new Person("Walter", "White", 50), //
new Person("Skyler", "White", 45), //
new Person("Saul", "Goodman", 42), //
new Person("Jesse", "Pinkman", 27))) //
.then() //
.block();
}
/**
* This sample performs a count, inserts data and performs a count again using reactive operator chaining.
*/
@Test
public void shouldInsertAndCountData() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
repository.count() //
.doOnNext(System.out::println) //
.thenMany(repository.save(Flux.just(new Person("Hank", "Schrader", 43), //
new Person("Mike", "Ehrmantraut", 62)))) //
.last() //
.flatMap(v -> repository.count()) //
.doOnNext(System.out::println) //
.doOnComplete(countDownLatch::countDown) //
.doOnError(throwable -> countDownLatch.countDown()) //
.subscribe();
countDownLatch.await();
}
/**
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void shouldPerformConversionBeforeResultProcessing() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
repository.findAll() //
.doOnNext(System.out::println) //
.doOnComplete(countDownLatch::countDown) //
.doOnError(throwable -> countDownLatch.countDown()) //
.subscribe();
countDownLatch.await();
}
/**
* A tailable cursor streams data using {@link Flux} as it arrives inside the capped collection.
*/
@Test
public void shouldStreamDataWithTailableCursor() throws Exception {
Cancellation cancellation = repository.findWithTailableCursorBy() //
.doOnNext(System.out::println) //
.doOnComplete(() -> System.out.println("Complete")) //
.doOnTerminate(() -> System.out.println("Terminated")) //
.subscribe();
Thread.sleep(100);
repository.save(new Person("Tuco", "Salamanca", 33)).subscribe();
Thread.sleep(100);
repository.save(new Person("Mike", "Ehrmantraut", 62)).subscribe();
Thread.sleep(100);
cancellation.dispose();
repository.save(new Person("Gus", "Fring", 53)).subscribe();
Thread.sleep(100);
}
/**
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithQueryDerivation() {
List<Person> whites = repository.findByLastname("White") //
.collectList() //
.block();
assertThat(whites).hasSize(2);
}
/**
* Fetch data using a string query.
*/
@Test
public void shouldQueryDataWithStringQuery() {
Person heisenberg = repository.findByFirstnameAndLastname("Walter", "White") //
.block();
assertThat(heisenberg).isNotNull();
}
/**
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithDeferredQueryDerivation() {
List<Person> whites = repository.findByLastname(Mono.just("White")) //
.collectList() //
.block();
assertThat(whites).hasSize(2);
}
/**
* Fetch data using query derivation and deferred parameter resolution.
*/
@Test
public void shouldQueryDataWithMixedDeferredQueryDerivation() {
Person heisenberg = repository.findByFirstnameAndLastname(Mono.just("Walter"), "White") //
.block();
assertThat(heisenberg).isNotNull();
}
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.people;
import static org.assertj.core.api.Assertions.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rx.Observable;
import rx.Single;
import rx.Subscription;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.CollectionOptions;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Integration test for {@link RxJava1PersonRepository} using RxJava1 types. Note that {@link ReactiveMongoOperations}
* is only available using Project Reactor types as the native Template API implementation does not come in multiple
* reactive flavors.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RxJava1PersonRepositoryIntegrationTest {
@Autowired RxJava1PersonRepository repository;
@Autowired ReactiveMongoOperations operations;
@Before
public void setUp() {
operations.collectionExists(Person.class) //
.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
.flatMap(o -> operations.createCollection(Person.class, new CollectionOptions(1024 * 1024, 100, true))) //
.then() //
.block();
repository
.save(Observable.just(new Person("Walter", "White", 50), //
new Person("Skyler", "White", 45), //
new Person("Saul", "Goodman", 42), //
new Person("Jesse", "Pinkman", 27))) //
.toBlocking() //
.last();
}
/**
* This sample performs a count, inserts data and performs a count again using reactive operator chaining.
*/
@Test
public void shouldInsertAndCountData() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
repository.count() //
.doOnSuccess(System.out::println) //
.toObservable() //
.switchMap(count -> repository.save(Observable.just(new Person("Hank", "Schrader", 43), //
new Person("Mike", "Ehrmantraut", 62)))) //
.last() //
.toSingle() //
.flatMap(v -> repository.count()) //
.doOnSuccess(System.out::println) //
.doAfterTerminate(countDownLatch::countDown) //
.doOnError(throwable -> countDownLatch.countDown()) //
.subscribe();
countDownLatch.await();
}
/**
* Note that the all object conversions are performed before the results are printed to the console.
*/
@Test
public void shouldPerformConversionBeforeResultProcessing() throws Exception {
CountDownLatch countDownLatch = new CountDownLatch(1);
repository.findAll() //
.doOnNext(System.out::println) //
.doOnCompleted(countDownLatch::countDown) //
.doOnError(throwable -> countDownLatch.countDown()) //
.subscribe();
countDownLatch.await();
}
/**
* A tailable cursor streams data using {@link Flux} as it arrives inside the capped collection.
*/
@Test
public void shouldStreamDataWithTailableCursor() throws Exception {
Subscription subscription = repository.findWithTailableCursorBy() //
.doOnNext(System.out::println) //
.doOnCompleted(() -> System.out.println("Complete")) //
.doOnTerminate(() -> System.out.println("Terminated")) //
.subscribe();
Thread.sleep(100);
repository.save(new Person("Tuco", "Salamanca", 33)).subscribe();
Thread.sleep(100);
repository.save(new Person("Mike", "Ehrmantraut", 62)).subscribe();
Thread.sleep(100);
subscription.unsubscribe();
repository.save(new Person("Gus", "Fring", 53)).subscribe();
Thread.sleep(100);
}
/**
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithQueryDerivation() {
List<Person> whites = repository.findByLastname("White") //
.toList() //
.toBlocking() //
.last();
assertThat(whites).hasSize(2);
}
/**
* Fetch data using a string query.
*/
@Test
public void shouldQueryDataWithStringQuery() {
Person heisenberg = repository.findByFirstnameAndLastname("Walter", "White") //
.toBlocking() //
.value();
assertThat(heisenberg).isNotNull();
}
/**
* Fetch data using query derivation.
*/
@Test
public void shouldQueryDataWithDeferredQueryDerivation() {
List<Person> whites = repository.findByLastname(Single.just("White")) //
.toList() //
.toBlocking() //
.single();
assertThat(whites).hasSize(2);
}
/**
* Fetch data using query derivation and deferred parameter resolution.
*/
@Test
public void shouldQueryDataWithMixedDeferredQueryDerivation() {
Person heisenberg = repository.findByFirstnameAndLastname(Single.just("Walter"), "White") //
.toBlocking().value();
assertThat(heisenberg).isNotNull();
}
}

View File

@@ -0,0 +1,4 @@
/**
* Package showing usage of Spring Data MongoDB Reactive Repositories and reactive MongoDB template.
*/
package example.springdata.mongodb.people;