├── fantasy_bookstore.png ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── .gitignore ├── src └── main │ ├── java │ └── com │ │ └── example │ │ └── bookstore │ │ ├── package-info.java │ │ ├── sync │ │ ├── package-info.java │ │ ├── atomic │ │ │ ├── package-info.java │ │ │ └── AtomicOrderService.java │ │ ├── transaction │ │ │ ├── package-info.java │ │ │ └── TransactionalOrderService.java │ │ ├── BookRepository.java │ │ ├── OrderRepository.java │ │ ├── OrderService.java │ │ ├── web │ │ │ └── SyncBookstoreHandler.java │ │ └── mongonative │ │ │ └── NativeMongoTransactionalOrderService.java │ │ ├── util │ │ ├── package-info.java │ │ ├── ConsoleOutMongoDBCommandListener.java │ │ └── TestDataLoader.java │ │ ├── reactive │ │ ├── transaction │ │ │ ├── package-info.java │ │ │ ├── ReactiveBookRepository.java │ │ │ └── ReactiveOrderService.java │ │ └── web │ │ │ └── ReactiveBookstoreHandler.java │ │ ├── BookSoldOutException.java │ │ ├── Customer.java │ │ ├── BookstoreHandler.java │ │ ├── Order.java │ │ ├── Book.java │ │ ├── AppProfiles.java │ │ └── FantasyBookstoreApplication.java │ └── resources │ ├── application.properties │ └── books.json ├── pom.xml ├── mvnw.cmd ├── README.md └── mvnw /fantasy_bookstore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/christophstrobl/mongodb-bookstore/HEAD/fantasy_bookstore.png -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/christophstrobl/mongodb-bookstore/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore; 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore.sync; 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/util/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore.util; 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/atomic/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore.sync.atomic; 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/transaction/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore.sync.transaction; 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/reactive/transaction/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @org.springframework.lang.NonNullApi 17 | package com.example.bookstore.reactive.transaction; 18 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # MongoDB 2 | server.port=8080 3 | spring.data.mongodb.database=fantasy-bookstore 4 | 5 | ################# AVAILABLE PROFILES ################################# 6 | # # 7 | # sa | Synchronous Atomic Operations # 8 | # stxn | Synchronous Multi Document Transactions with MongoClient # 9 | # stx | Synchronous Multi Document Transactions with Spring # 10 | # rtx | Reactive Multi Document Transactions with Spring # 11 | # rcs | Reactive Change Streams # 12 | # retry | Retry on error # 13 | # reset | Reset Application and test data # 14 | # # 15 | ###################################################################### 16 | spring.profiles.active=reset,stx 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/BookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync; 17 | 18 | import org.springframework.data.repository.CrudRepository; 19 | 20 | import com.example.bookstore.Book; 21 | 22 | /** 23 | * @author Christoph Strobl 24 | */ 25 | public interface BookRepository extends CrudRepository {} 26 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/OrderRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync; 17 | 18 | import org.springframework.data.repository.CrudRepository; 19 | 20 | import com.example.bookstore.Order; 21 | 22 | /** 23 | * @author Christoph Strobl 24 | */ 25 | public interface OrderRepository extends CrudRepository {} 26 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/BookSoldOutException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | /** 19 | * Oh no! It happened, we've run out of {@link Book books}. 20 | * 21 | * @author Christoph Strobl 22 | */ 23 | public class BookSoldOutException extends RuntimeException { 24 | 25 | private final Book book; 26 | 27 | public BookSoldOutException(Book book) { 28 | this.book = book; 29 | } 30 | 31 | @Override 32 | public String getMessage() { 33 | return String.format("o_O we've run out of %s by %s", book.getTitle(), book.getAuthors()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/reactive/transaction/ReactiveBookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.reactive.transaction; 17 | 18 | import org.springframework.context.annotation.Profile; 19 | import org.springframework.data.repository.reactive.ReactiveCrudRepository; 20 | 21 | import com.example.bookstore.AppProfiles; 22 | import com.example.bookstore.Book; 23 | 24 | /** 25 | * @author Christoph Strobl 26 | */ 27 | @Profile({ AppProfiles.REACTIVE_TRANSACTION }) 28 | public interface ReactiveBookRepository extends ReactiveCrudRepository { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/OrderService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync; 17 | 18 | import org.springframework.retry.annotation.Backoff; 19 | import org.springframework.retry.annotation.Retryable; 20 | 21 | import com.example.bookstore.Book; 22 | import com.example.bookstore.Customer; 23 | import com.example.bookstore.Order; 24 | 25 | /** 26 | * @author Christoph Strobl 27 | */ 28 | public interface OrderService { 29 | 30 | /** 31 | * Place the order for a specific {@link Book}. 32 | * 33 | * @param customer 34 | * @param book 35 | * @return 36 | */ 37 | @Retryable(backoff = @Backoff(5000)) 38 | Order buy(Customer customer, Book book); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/Customer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | import lombok.Value; 19 | 20 | import org.springframework.data.annotation.Id; 21 | 22 | /** 23 | * @author Christoph Strobl 24 | */ 25 | @Value 26 | public class Customer { 27 | 28 | @Id String email; 29 | 30 | public static Customer of(String alias) { 31 | 32 | switch (alias) { 33 | 34 | case "christoph": 35 | return Customer.christoph(); 36 | case "jeff": 37 | return Customer.jeff(); 38 | case "oliver": 39 | return Customer.oliver(); 40 | default: 41 | return new Customer(alias); 42 | } 43 | } 44 | 45 | public static Customer christoph() { 46 | return new Customer("cstrobl@pivotal.io"); 47 | } 48 | 49 | public static Customer jeff() { 50 | return new Customer("jeff.yemin@mongodb.com"); 51 | } 52 | 53 | public static Customer oliver() { 54 | return new Customer("ogierke@pivotal.io"); 55 | } 56 | 57 | public static Customer guest() { 58 | return new Customer("guest@fantasy-bookstore.io"); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/BookstoreHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | import reactor.core.publisher.Mono; 19 | 20 | import org.springframework.web.reactive.function.server.ServerRequest; 21 | import org.springframework.web.reactive.function.server.ServerResponse; 22 | 23 | /** 24 | * Web request handler for webflux. 25 | * 26 | * @author Christoph Strobl 27 | */ 28 | public interface BookstoreHandler { 29 | 30 | /** 31 | * Process a {@link ServerRequest} for a list of {@link Book books}. 32 | * 33 | * @param request 34 | * @return 35 | */ 36 | Mono books(ServerRequest request); 37 | 38 | /** 39 | * Process a {@link ServerRequest} for a single {@link Book}. 40 | * 41 | * @param request 42 | * @return 43 | */ 44 | Mono book(ServerRequest request); 45 | 46 | /** 47 | * Process a {@link ServerRequest} to {@link Order order} a specific {@link Book}. 48 | * 49 | * @param request 50 | * @return 51 | */ 52 | Mono order(ServerRequest request); 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/Order.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | import lombok.Value; 19 | 20 | import java.util.Date; 21 | import java.util.List; 22 | 23 | import org.springframework.data.mongodb.core.mapping.DBRef; 24 | import org.springframework.data.mongodb.core.mapping.Field; 25 | import org.springframework.lang.Nullable; 26 | 27 | /** 28 | * An order as simple as it can be. 29 | * 30 | *
31 |  * 
32 |  * {
33 |  *     "by" : "cstrobl@pivotal.io",
34 |  *     "date" : ISODate("2018-08-27T10:11:59.853Z"),
35 |  *     "books" : [ { "$ref" : "books", "$id" : "f430cb49" } ]
36 |  * }
37 |  *
38 |  * 
39 |  * 
40 | * 41 | * @author Christoph Strobl 42 | * @see MongoDB - Data Model 43 | * Examples and Patterns 44 | */ 45 | @Value 46 | public class Order { 47 | 48 | @Field("by") // 49 | String customer; 50 | Date date; 51 | 52 | @Nullable // 53 | @DBRef List books; 54 | 55 | public Order(String customer, Date date) { 56 | this(customer, date, null); 57 | } 58 | 59 | public Order(String customer, Date date, @Nullable List books) { 60 | 61 | this.customer = customer; 62 | this.date = date; 63 | this.books = books; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/resources/books.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "_id": "jeffs-book", 4 | "title": "The Man in the High Castle", 5 | "author": [ 6 | "Philip K. Dick" 7 | ], 8 | "published_date": "1962-01-10", 9 | "pages": 240, 10 | "language": "English", 11 | "publisher_id": "Putnam", 12 | "available": 3, 13 | "checkout": [] 14 | }, 15 | { 16 | "_id": "bb4e114f", 17 | "title": "The Painted Man", 18 | "author": [ 19 | "Peter V. Brett" 20 | ], 21 | "published_date": "2009-08-01", 22 | "pages": 544, 23 | "language": "English", 24 | "publisher_id": "Harper Collins Publishers", 25 | "available": 3, 26 | "checkout": [] 27 | }, 28 | { 29 | "_id": "1c56b2b0", 30 | "title": "The Desert Spear", 31 | "author": [ 32 | "Peter V. Brett" 33 | ], 34 | "published_date": "2010-01-04", 35 | "pages": 560, 36 | "language": "English", 37 | "publisher_id": "Harper Collins Publishers", 38 | "available": 3, 39 | "checkout": [] 40 | }, 41 | { 42 | "_id": "ade1cb9b", 43 | "title": "Daylight War", 44 | "author": [ 45 | "Peter V. Brett" 46 | ], 47 | "published_date": "2013-11-03", 48 | "pages": 804, 49 | "language": "English", 50 | "publisher_id": "Harper Collins Publishers", 51 | "available": 3, 52 | "checkout": [] 53 | }, 54 | { 55 | "_id": "c5a809ef", 56 | "title": "The Skull Throne", 57 | "author": [ 58 | "Peter V. Brett" 59 | ], 60 | "published_date": "2015-31-03", 61 | "pages": 704, 62 | "language": "English", 63 | "publisher_id": "Harper Collins Publishers", 64 | "available": 3, 65 | "checkout": [] 66 | }, 67 | { 68 | "_id": "f430cb49", 69 | "title": "The Core", 70 | "author": [ 71 | "Peter V. Brett" 72 | ], 73 | "published_date": "2017-28-09", 74 | "pages": 880, 75 | "language": "English", 76 | "publisher_id": "Harper Collins Publishers", 77 | "available": 3, 78 | "checkout": [] 79 | } 80 | ] -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/Book.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | import lombok.AccessLevel; 19 | import lombok.Data; 20 | import lombok.experimental.FieldDefaults; 21 | 22 | import java.util.List; 23 | 24 | import org.springframework.data.annotation.Id; 25 | import org.springframework.data.mongodb.core.mapping.Document; 26 | import org.springframework.data.mongodb.core.mapping.Field; 27 | 28 | /** 29 | * A book as simple as it can be. 30 | * 31 | *
32 |  * 
33 |  * {
34 |  *     _id: 123456789,
35 |  *     title: "MongoDB: The Definitive Guide",
36 |  *     author: [ "Kristina Chodorow", "Mike Dirolf" ],
37 |  *     published_date: ISODate("2010-09-24"),
38 |  *     pages: 216,
39 |  *     language: "English",
40 |  *     publisher_id: "oreilly",
41 |  *     available: 3
42 |  * }
43 |  *
44 |  * 
45 |  * 
46 | * 47 | * @author Christoph Strobl 48 | * @see MongoDB - Data Model 49 | * Examples and Patterns 50 | */ 51 | @Data 52 | @Document("books") 53 | @FieldDefaults(level = AccessLevel.PRIVATE) 54 | public class Book { 55 | 56 | @Id String id; 57 | String title; 58 | 59 | @Field("author") List authors; 60 | 61 | @Field("published_date") // 62 | String publishDate; 63 | 64 | int pages; 65 | String language; 66 | 67 | @Field("publisher_id") // 68 | String publisherId; 69 | 70 | @Field("available") // 71 | int stock; 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/AppProfiles.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | /** 19 | * Just a simple collection of supported {@link org.springframework.context.annotation.Profile} values used for 20 | * configuration. 21 | * 22 | * @author Christoph Strobl 23 | */ 24 | public final class AppProfiles { 25 | 26 | /** 27 | * Spring {@link org.springframework.context.annotation.Profile} value to reset the application to its initial state. 28 | */ 29 | public static final String RESET = "reset"; 30 | 31 | /** 32 | * Spring {@link org.springframework.context.annotation.Profile} to be used for the synchronous atomic 33 | * {@link org.bson.Document} update sample. 34 | */ 35 | public static final String SYNC_ATOMIC = "sa"; 36 | 37 | /** 38 | * Spring {@link org.springframework.context.annotation.Profile} to be used for the 39 | * {@link com.mongodb.client.MongoClient} synchronous transactional sample. 40 | */ 41 | public static final String NATIVE_SYNC_TRANSACTION = "stxn"; 42 | 43 | /** 44 | * Spring {@link org.springframework.context.annotation.Profile} to be used for the synchronous transactional sample. 45 | */ 46 | public static final String SYNC_TRANSACTION = "stx"; 47 | 48 | /** 49 | * Spring {@link org.springframework.context.annotation.Profile} to be used for the reactive transactional sample. 50 | */ 51 | public static final String REACTIVE_TRANSACTION = "rtx"; 52 | 53 | /** 54 | * Spring {@link org.springframework.context.annotation.Profile} to activate retry. 55 | */ 56 | public static final String RETRYABLE_TRANSACTION = "retry"; 57 | 58 | /** 59 | * Spring {@link org.springframework.context.annotation.Profile} to be used to demonstrate change streams. 60 | */ 61 | public static final String REACTIVE_CHANGESTREAMS = "rcs"; 62 | 63 | private AppProfiles() { /* u can't touch this */} 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/reactive/web/ReactiveBookstoreHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.reactive.web; 17 | 18 | import static org.springframework.web.reactive.function.server.ServerResponse.*; 19 | 20 | import lombok.RequiredArgsConstructor; 21 | import reactor.core.publisher.Mono; 22 | 23 | import org.springframework.context.annotation.Profile; 24 | import org.springframework.stereotype.Component; 25 | import org.springframework.web.reactive.function.server.ServerRequest; 26 | import org.springframework.web.reactive.function.server.ServerResponse; 27 | 28 | import com.example.bookstore.AppProfiles; 29 | import com.example.bookstore.Book; 30 | import com.example.bookstore.BookstoreHandler; 31 | import com.example.bookstore.Customer; 32 | import com.example.bookstore.Order; 33 | import com.example.bookstore.reactive.transaction.ReactiveBookRepository; 34 | import com.example.bookstore.reactive.transaction.ReactiveOrderService; 35 | 36 | /** 37 | * Reactive {@link BookstoreHandler} implementation. 38 | * 39 | * @author Christoph Strobl 40 | */ 41 | @Component 42 | @Profile({ AppProfiles.REACTIVE_TRANSACTION }) 43 | @RequiredArgsConstructor 44 | public class ReactiveBookstoreHandler implements BookstoreHandler { 45 | 46 | private final ReactiveBookRepository bookRepository; 47 | private final ReactiveOrderService orderService; 48 | 49 | @Override 50 | public Mono books(ServerRequest request) { 51 | 52 | return ok().body(bookRepository.findAll(), Book.class); 53 | } 54 | 55 | @Override 56 | public Mono book(ServerRequest request) { 57 | return ok().body(bookRepository.findById(request.pathVariable("book")), Book.class); 58 | } 59 | 60 | @Override 61 | public Mono order(ServerRequest request) { 62 | 63 | Customer customer = Customer.of(request.queryParam("customer").orElse(Customer.guest().getEmail())); 64 | 65 | return ok() // 66 | .body(bookRepository.findById(request.pathVariable("book")) // 67 | .flatMap(book -> orderService.buy(customer, book)), Order.class); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/util/ConsoleOutMongoDBCommandListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.util; 17 | 18 | import org.bson.json.JsonMode; 19 | import org.bson.json.JsonWriterSettings; 20 | 21 | import com.mongodb.event.CommandFailedEvent; 22 | import com.mongodb.event.CommandListener; 23 | import com.mongodb.event.CommandStartedEvent; 24 | import com.mongodb.event.CommandSucceededEvent; 25 | 26 | /** 27 | * @author Christoph Strobl 28 | */ 29 | public enum ConsoleOutMongoDBCommandListener implements CommandListener { 30 | 31 | INSTANCE; 32 | 33 | @Override 34 | public void commandStarted(CommandStartedEvent event) { 35 | 36 | System.out.println("\nSending Command: " + event.getCommandName()); 37 | System.out.println(bgColored(COLOR.CYAN, "-->") + " " 38 | + event.getCommand().toJson(JsonWriterSettings.builder().indent(true).outputMode(JsonMode.RELAXED).build())); 39 | } 40 | 41 | @Override 42 | public void commandSucceeded(CommandSucceededEvent event) { 43 | System.out.println(bgColored(COLOR.GREEN, "<--") + " " + event.getResponse()); 44 | } 45 | 46 | @Override 47 | public void commandFailed(CommandFailedEvent event) { 48 | System.out.println(bgColored(COLOR.RED, "-X-") + " " + event.getThrowable().getMessage()); 49 | } 50 | 51 | static String bgColored(COLOR bgColor, String text) { 52 | return colored(COLOR.DEFAULT, bgColor, text); 53 | } 54 | 55 | static String colored(COLOR fg, COLOR bg, String text) { 56 | return (char) 27 + "[" + fg.getFgColorCode() + ";" + bg.getBgColorCode() + "m" + text + (char) 27 + "[" 57 | + COLOR.DEFAULT.getFgColorCode() + ";" + COLOR.DEFAULT.getBgColorCode() + "m"; 58 | } 59 | 60 | enum COLOR { 61 | 62 | BLACK(30), RED(31), GREEN(32), YELLOW(33), BLUE(34), MAGENTA(35), CYAN(36), WHITE(37), DEFAULT(39); 63 | 64 | int fgColorCode; 65 | 66 | COLOR(int fgColorCode) { 67 | this.fgColorCode = fgColorCode; 68 | } 69 | 70 | public int getFgColorCode() { 71 | return fgColorCode; 72 | } 73 | 74 | public int getBgColorCode() { 75 | return getFgColorCode() + 10; 76 | } 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/reactive/transaction/ReactiveOrderService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.reactive.transaction; 17 | 18 | import static org.springframework.data.mongodb.core.query.Criteria.*; 19 | import static org.springframework.data.mongodb.core.query.Query.*; 20 | 21 | import lombok.RequiredArgsConstructor; 22 | import reactor.core.publisher.Mono; 23 | 24 | import java.util.Arrays; 25 | import java.util.Date; 26 | 27 | import org.springframework.context.annotation.Profile; 28 | import org.springframework.data.mongodb.core.ReactiveMongoOperations; 29 | import org.springframework.data.mongodb.core.query.Update; 30 | import org.springframework.stereotype.Service; 31 | 32 | import com.example.bookstore.AppProfiles; 33 | import com.example.bookstore.Book; 34 | import com.example.bookstore.BookSoldOutException; 35 | import com.example.bookstore.Customer; 36 | import com.example.bookstore.Order; 37 | 38 | /** 39 | * Reactive OrderService using MongoDB 4.0 transactions. 40 | * 41 | * @author Christoph Strobl 42 | */ 43 | @Service 44 | @Profile({ AppProfiles.REACTIVE_TRANSACTION }) 45 | @RequiredArgsConstructor 46 | public class ReactiveOrderService { 47 | 48 | private final ReactiveMongoOperations mongoOperations; 49 | 50 | /** 51 | * Place the order for a specific {@link Book}. 52 | * 53 | * @param customer 54 | * @param book 55 | * @return 56 | */ 57 | public Mono buy(Customer customer, Book book) { 58 | 59 | return mongoOperations.inTransaction().execute(action -> { 60 | 61 | return action.save(new Order(customer.getEmail(), new Date(), Arrays.asList(book))) 62 | 63 | .flatMap(order -> { 64 | 65 | return action.update(Book.class) // 66 | .matching(query(where("id").is(book.getId()).and("stock").gt(0))) // 67 | .apply(new Update().inc("stock", -1)) // 68 | .first() // 69 | .map(result -> { 70 | 71 | if (result.getModifiedCount() == 0) { 72 | throw new BookSoldOutException(book); 73 | } 74 | 75 | return order; 76 | }); 77 | }); 78 | }).next(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/atomic/AtomicOrderService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync.atomic; 17 | 18 | import static org.springframework.data.mongodb.core.query.Criteria.*; 19 | import static org.springframework.data.mongodb.core.query.Query.*; 20 | 21 | import lombok.RequiredArgsConstructor; 22 | 23 | import java.util.Arrays; 24 | import java.util.Date; 25 | 26 | import org.springframework.beans.factory.annotation.Qualifier; 27 | import org.springframework.context.annotation.Profile; 28 | import org.springframework.data.mongodb.core.MongoOperations; 29 | import org.springframework.data.mongodb.core.query.Update; 30 | import org.springframework.stereotype.Service; 31 | 32 | import com.example.bookstore.AppProfiles; 33 | import com.example.bookstore.Book; 34 | import com.example.bookstore.BookSoldOutException; 35 | import com.example.bookstore.Customer; 36 | import com.example.bookstore.Order; 37 | import com.example.bookstore.sync.BookRepository; 38 | import com.example.bookstore.sync.OrderService; 39 | import com.mongodb.client.result.UpdateResult; 40 | 41 | /** 42 | * Synchronous {@link OrderService} implementation using the atomic document update model. 43 | * 44 | * @author Christoph Strobl 45 | */ 46 | @Service 47 | @Qualifier("atomic-document-order-service") 48 | @Profile({ AppProfiles.SYNC_ATOMIC }) 49 | @RequiredArgsConstructor 50 | public class AtomicOrderService implements OrderService { 51 | 52 | private final BookRepository bookRepository; 53 | private final MongoOperations mongoOperations; 54 | 55 | @Override 56 | public Order buy(Customer customer, Book book) { 57 | 58 | Order order = new Order(customer.getEmail(), new Date()); 59 | return checkout(order, book); 60 | } 61 | 62 | private Order checkout(Order order, Book book) { 63 | 64 | UpdateResult result = mongoOperations.update(Book.class) // 65 | .matching(query(where("id").is(book.getId()).and("stock").gt(0))) // 66 | .apply(new Update().inc("stock", -1).push("checkout", order)) // 67 | .first(); 68 | 69 | if (result.getModifiedCount() != 1) { 70 | throw new BookSoldOutException(book); 71 | } 72 | 73 | return new Order(order.getCustomer(), order.getDate(), Arrays.asList(book)); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/util/TestDataLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.util; 17 | 18 | import lombok.RequiredArgsConstructor; 19 | 20 | import java.nio.charset.StandardCharsets; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.stream.Collectors; 24 | 25 | import javax.annotation.PostConstruct; 26 | 27 | import org.bson.Document; 28 | import org.springframework.boot.json.JacksonJsonParser; 29 | import org.springframework.context.annotation.Profile; 30 | import org.springframework.core.io.ClassPathResource; 31 | import org.springframework.core.io.Resource; 32 | import org.springframework.data.mongodb.core.MongoTemplate; 33 | import org.springframework.stereotype.Component; 34 | import org.springframework.util.StreamUtils; 35 | 36 | import com.example.bookstore.AppProfiles; 37 | import com.example.bookstore.Book; 38 | import com.example.bookstore.Order; 39 | import com.mongodb.client.MongoCollection; 40 | 41 | /** 42 | * A simple component that resets the test data. 43 | * 44 | * @author Christoph Strobl 45 | */ 46 | @Component 47 | @Profile(AppProfiles.RESET) 48 | @RequiredArgsConstructor 49 | class TestDataLoader { 50 | 51 | private final MongoTemplate template; 52 | 53 | void resetTestDataFor(Class type) throws Exception { 54 | resetTestDataFor(template.getCollectionName(type)); 55 | } 56 | 57 | void resetTestDataFor(String collection) throws Exception { 58 | 59 | if (template.collectionExists(collection)) { 60 | template.getCollection(collection).deleteMany(new Document()); 61 | } else { 62 | template.createCollection(collection); 63 | } 64 | 65 | Resource dataFile = new ClassPathResource(collection + ".json"); 66 | 67 | if (dataFile.exists()) { 68 | 69 | List objects = new JacksonJsonParser() // 70 | .parseList(StreamUtils.copyToString(dataFile.getInputStream(), StandardCharsets.UTF_8)).stream() 71 | .map(Map.class::cast).collect(Collectors.toList()); 72 | 73 | MongoCollection mongoCollection = template.getCollection(collection); 74 | 75 | objects.forEach(it -> mongoCollection.insertOne(new Document((Map) it))); 76 | } 77 | } 78 | 79 | @PostConstruct 80 | public void init() throws Exception { 81 | 82 | resetTestDataFor(Book.class); 83 | resetTestDataFor(Order.class); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/web/SyncBookstoreHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync.web; 17 | 18 | import static org.springframework.web.reactive.function.server.ServerResponse.*; 19 | import static reactor.core.publisher.Mono.*; 20 | 21 | import lombok.RequiredArgsConstructor; 22 | import reactor.core.publisher.Flux; 23 | import reactor.core.publisher.Mono; 24 | 25 | import org.springframework.context.annotation.Profile; 26 | import org.springframework.stereotype.Component; 27 | import org.springframework.web.reactive.function.server.ServerRequest; 28 | import org.springframework.web.reactive.function.server.ServerResponse; 29 | 30 | import com.example.bookstore.AppProfiles; 31 | import com.example.bookstore.Book; 32 | import com.example.bookstore.BookstoreHandler; 33 | import com.example.bookstore.Customer; 34 | import com.example.bookstore.Order; 35 | import com.example.bookstore.sync.BookRepository; 36 | import com.example.bookstore.sync.OrderService; 37 | 38 | /** 39 | * Synchronous {@link BookstoreHandler} implementation. 40 | * 41 | * @author Christoph Strobl 42 | */ 43 | @Component 44 | @Profile({ AppProfiles.SYNC_ATOMIC, AppProfiles.SYNC_TRANSACTION, AppProfiles.NATIVE_SYNC_TRANSACTION }) 45 | @RequiredArgsConstructor 46 | public class SyncBookstoreHandler implements BookstoreHandler { 47 | 48 | private final BookRepository bookRepository; 49 | private final OrderService orderService; 50 | 51 | @Override 52 | public Mono books(ServerRequest request) { 53 | return ok().body(Flux.fromIterable(bookRepository.findAll()), Book.class); 54 | } 55 | 56 | @Override 57 | public Mono book(ServerRequest request) { 58 | return ok().body(just(bookById(request)), Book.class); 59 | } 60 | 61 | @Override 62 | public Mono order(ServerRequest request) { 63 | 64 | Customer customer = Customer.of(request.queryParam("customer").orElse(Customer.guest().getEmail())); 65 | 66 | return ok().body(just(orderService.buy(customer, bookById(request))), Order.class); 67 | } 68 | 69 | private Book bookById(ServerRequest request) { 70 | 71 | return bookRepository.findById(request.pathVariable("book")).orElseThrow( 72 | () -> new RuntimeException(String.format("No book found for id %s", request.pathVariable("book")))); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/transaction/TransactionalOrderService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync.transaction; 17 | 18 | import static org.springframework.data.mongodb.core.query.Criteria.*; 19 | import static org.springframework.data.mongodb.core.query.Query.*; 20 | 21 | import lombok.RequiredArgsConstructor; 22 | 23 | import java.util.Arrays; 24 | import java.util.Date; 25 | 26 | import org.springframework.beans.factory.annotation.Qualifier; 27 | import org.springframework.context.annotation.Profile; 28 | import org.springframework.data.mongodb.MongoTransactionManager; 29 | import org.springframework.data.mongodb.core.MongoOperations; 30 | import org.springframework.data.mongodb.core.query.Update; 31 | import org.springframework.stereotype.Service; 32 | import org.springframework.transaction.support.TransactionTemplate; 33 | 34 | import com.example.bookstore.AppProfiles; 35 | import com.example.bookstore.Book; 36 | import com.example.bookstore.BookSoldOutException; 37 | import com.example.bookstore.Customer; 38 | import com.example.bookstore.Order; 39 | import com.example.bookstore.sync.OrderRepository; 40 | import com.example.bookstore.sync.OrderService; 41 | import com.mongodb.client.result.UpdateResult; 42 | 43 | /** 44 | * Synchronous {@link OrderService} implementation using transactions. 45 | * 46 | * @author Christoph Strobl 47 | */ 48 | @Service 49 | @Qualifier("transactional-order-service") 50 | @Profile({ AppProfiles.SYNC_TRANSACTION }) 51 | @RequiredArgsConstructor 52 | public class TransactionalOrderService implements OrderService { 53 | 54 | private final OrderRepository orderRepository; 55 | private final MongoOperations mongoOps; 56 | private final MongoTransactionManager txManager; 57 | 58 | @Override 59 | public Order buy(Customer customer, Book book) { 60 | 61 | TransactionTemplate tt = new TransactionTemplate(txManager); 62 | 63 | return tt.execute(action -> { 64 | 65 | Order order = new Order(customer.getEmail(), new Date(), Arrays.asList(book)); 66 | orderRepository.save(order); 67 | 68 | UpdateResult result = mongoOps.update(Book.class) // 69 | .matching(query(where("id").is(book.getId()).and("stock").gt(0))) // 70 | .apply(new Update().inc("stock", -1)) // 71 | .first(); 72 | 73 | if (result.getModifiedCount() != 1) { 74 | throw new BookSoldOutException(book); 75 | } 76 | 77 | return order; 78 | }); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/sync/mongonative/NativeMongoTransactionalOrderService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore.sync.mongonative; 17 | 18 | import static com.mongodb.client.model.Filters.*; 19 | import static com.mongodb.client.model.Updates.*; 20 | 21 | import lombok.RequiredArgsConstructor; 22 | 23 | import java.util.Arrays; 24 | import java.util.Date; 25 | import java.util.stream.Collectors; 26 | 27 | import org.bson.Document; 28 | import org.springframework.beans.factory.annotation.Qualifier; 29 | import org.springframework.beans.factory.annotation.Value; 30 | import org.springframework.context.annotation.Profile; 31 | import org.springframework.stereotype.Service; 32 | 33 | import com.example.bookstore.AppProfiles; 34 | import com.example.bookstore.Book; 35 | import com.example.bookstore.BookSoldOutException; 36 | import com.example.bookstore.Customer; 37 | import com.example.bookstore.Order; 38 | import com.example.bookstore.sync.OrderService; 39 | import com.mongodb.DBRef; 40 | import com.mongodb.client.ClientSession; 41 | import com.mongodb.client.MongoClient; 42 | import com.mongodb.client.MongoDatabase; 43 | import com.mongodb.client.result.UpdateResult; 44 | 45 | /** 46 | * Synchronous {@link OrderService} implementation using transactions directly via {@link MongoClient}. 47 | * 48 | * @author Christoph Strobl 49 | */ 50 | @Service 51 | @Qualifier("native-transactional-order-service") 52 | @Profile({ AppProfiles.NATIVE_SYNC_TRANSACTION }) 53 | @RequiredArgsConstructor 54 | public class NativeMongoTransactionalOrderService implements OrderService { 55 | 56 | private final MongoClient client; 57 | private @Value("${spring.data.mongodb.database}") String databaseName; 58 | 59 | @Override 60 | public Order buy(Customer customer, Book book) { 61 | 62 | Order order = new Order(customer.getEmail(), new Date(), Arrays.asList(book)); 63 | 64 | MongoDatabase database = client.getDatabase(databaseName); 65 | try (ClientSession session = client.startSession()) { 66 | 67 | session.startTransaction(); 68 | 69 | database.getCollection("order").insertOne(session, toDocument(order)); 70 | 71 | UpdateResult result = database.getCollection("books").updateOne(session, // 72 | and(eq("_id", book.getId()), gt("available", 0)), // 73 | inc("available", -1)); // 74 | 75 | if (result.getModifiedCount() != 1) { 76 | throw new BookSoldOutException(book); 77 | } 78 | 79 | session.commitTransaction(); 80 | } 81 | 82 | return order; 83 | } 84 | 85 | private static Document toDocument(Order order) { 86 | 87 | return new Document("by", order.getCustomer()) // 88 | .append("date", order.getDate()) // 89 | .append("books", 90 | order.getBooks().stream().map(it -> new DBRef("books", it.getId())).collect(Collectors.toList())); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | fantasy-bookstore 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | Fantasy-Bookstore 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.1.0.M4 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Lovelace-GA 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-mongodb 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-mongodb-reactive 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-webflux 40 | 41 | 42 | 43 | org.projectlombok 44 | lombok 45 | 1.18.0 46 | 47 | 48 | 49 | org.springframework.retry 50 | spring-retry 51 | 52 | 53 | org.springframework 54 | spring-aop 55 | 56 | 57 | org.aspectj 58 | aspectjweaver 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-test 64 | test 65 | 66 | 67 | io.projectreactor 68 | reactor-test 69 | test 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-maven-plugin 78 | 79 | 80 | 81 | 82 | 83 | 84 | spring-snapshots 85 | Spring Snapshots 86 | https://repo.spring.io/snapshot 87 | 88 | true 89 | 90 | 91 | 92 | spring-milestones 93 | Spring Milestones 94 | https://repo.spring.io/milestone 95 | 96 | false 97 | 98 | 99 | 100 | 101 | 102 | 103 | spring-snapshots 104 | Spring Snapshots 105 | https://repo.spring.io/snapshot 106 | 107 | true 108 | 109 | 110 | 111 | spring-milestones 112 | Spring Milestones 113 | https://repo.spring.io/milestone 114 | 115 | false 116 | 117 | 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /src/main/java/com/example/bookstore/FantasyBookstoreApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.bookstore; 17 | 18 | import static org.springframework.web.reactive.function.server.RequestPredicates.*; 19 | 20 | import javax.annotation.PostConstruct; 21 | 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.beans.factory.annotation.Value; 24 | import org.springframework.boot.SpringApplication; 25 | import org.springframework.boot.autoconfigure.SpringBootApplication; 26 | import org.springframework.context.annotation.Bean; 27 | import org.springframework.context.annotation.Configuration; 28 | import org.springframework.context.annotation.Profile; 29 | import org.springframework.data.mongodb.MongoDbFactory; 30 | import org.springframework.data.mongodb.MongoTransactionManager; 31 | import org.springframework.data.mongodb.core.ChangeStreamOptions; 32 | import org.springframework.data.mongodb.core.MongoTemplate; 33 | import org.springframework.data.mongodb.core.ReactiveMongoTemplate; 34 | import org.springframework.retry.annotation.EnableRetry; 35 | import org.springframework.web.reactive.function.server.RouterFunction; 36 | import org.springframework.web.reactive.function.server.RouterFunctions; 37 | import org.springframework.web.reactive.function.server.ServerResponse; 38 | 39 | import com.example.bookstore.util.ConsoleOutMongoDBCommandListener; 40 | import com.mongodb.MongoClientSettings; 41 | import com.mongodb.client.MongoClients; 42 | 43 | /** 44 | * @author Christoph Strobl 45 | */ 46 | @SpringBootApplication 47 | public class FantasyBookstoreApplication { 48 | 49 | public static void main(String[] args) { 50 | SpringApplication.run(FantasyBookstoreApplication.class, args); 51 | } 52 | 53 | /** 54 | * The default configuration to apply no matter what. 55 | */ 56 | @Configuration 57 | class DefaultConfiguration { 58 | 59 | @Autowired MongoTemplate template; 60 | 61 | @Bean 62 | com.mongodb.client.MongoClient mongoClient() { 63 | 64 | MongoClientSettings settings = MongoClientSettings.builder() // 65 | .addCommandListener(ConsoleOutMongoDBCommandListener.INSTANCE) // 66 | .build(); 67 | 68 | return MongoClients.create(settings); 69 | } 70 | 71 | /** 72 | * {@link RouterFunction Routes} to interact with the MongoDB Bookstore Application delegating the processing of 73 | * {@link org.springframework.web.reactive.function.server.ServerRequest requests} to the {@link BookstoreHandler}. 74 | * 75 | * @param handler 76 | * @return 77 | */ 78 | @Bean 79 | RouterFunction routerFunction(BookstoreHandler handler) { 80 | 81 | return RouterFunctions.route(GET("/books"), handler::books) // 82 | .andRoute(GET("/book/{book}"), handler::book) // 83 | .andRoute(POST("/book/{book}/order"), handler::order); 84 | } 85 | 86 | /** 87 | * Just make sure to have everything at hand so we do not run into issues when accessing (potentially non existing) 88 | * collections in a transaction. 89 | */ 90 | @PostConstruct 91 | public void init() { 92 | 93 | if (!template.collectionExists(Order.class)) { 94 | template.createCollection(Order.class); 95 | } 96 | if (!template.collectionExists(Book.class)) { 97 | template.createCollection(Book.class); 98 | } 99 | } 100 | } 101 | 102 | /** 103 | * Additional configuration for: synchronous atomic document update. 104 | */ 105 | @Configuration 106 | @Profile(AppProfiles.SYNC_ATOMIC) 107 | class SyncConfiguration { 108 | 109 | } 110 | 111 | /** 112 | * Additional configuration for: synchronous transactions plainly using the {@link com.mongodb.client.MongoClient}. 113 | */ 114 | @Configuration 115 | @Profile(AppProfiles.NATIVE_SYNC_TRANSACTION) 116 | class SyncNativeMongoTransactionConfiguration { 117 | 118 | } 119 | 120 | /** 121 | * Additional configuration for: synchronous Spring managed transactions. 122 | */ 123 | @Configuration 124 | @Profile(AppProfiles.SYNC_TRANSACTION) 125 | class SyncSpringTransactionConfiguration { 126 | 127 | @Bean 128 | MongoTransactionManager txManager(MongoDbFactory dbFactory) { 129 | return new MongoTransactionManager(dbFactory); 130 | } 131 | } 132 | 133 | /** 134 | * Additional configuration for: reactive transactions. 135 | */ 136 | @Configuration 137 | @Profile(AppProfiles.REACTIVE_TRANSACTION) 138 | class ReactiveTransactionConfiguration { 139 | 140 | @Bean 141 | com.mongodb.reactivestreams.client.MongoClient reactiveMongoClient() { 142 | 143 | MongoClientSettings settings = MongoClientSettings.builder() // 144 | .addCommandListener(ConsoleOutMongoDBCommandListener.INSTANCE) // 145 | .build(); 146 | 147 | return com.mongodb.reactivestreams.client.MongoClients.create(settings); 148 | } 149 | } 150 | 151 | /** 152 | * Additional configuration for: Change Streams 153 | */ 154 | @Configuration 155 | @Profile(AppProfiles.REACTIVE_CHANGESTREAMS) 156 | class ReactiveChangeStreamConfiguration { 157 | 158 | @Value("${spring.data.mongodb.database}") String database; 159 | 160 | @PostConstruct 161 | public void init() { 162 | 163 | new ReactiveMongoTemplate(com.mongodb.reactivestreams.client.MongoClients.create(), database) // 164 | .changeStream("order", ChangeStreamOptions.empty(), Order.class) // 165 | .doOnNext(System.out::println) // 166 | .subscribe(); 167 | } 168 | } 169 | 170 | /** 171 | * Additional configuration for: Retry on write conflict 172 | */ 173 | @Configuration 174 | @Profile(AppProfiles.RETRYABLE_TRANSACTION) 175 | @EnableRetry 176 | class RetryableTransactionConfiguration { 177 | 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Welcome to the ![Fantasy Bookstore](/fantasy_bookstore.png?raw=true) 2 | 3 | The _Fantasy Bookstore_ is a tiny [SpringBoot](https://github.com/spring-projects/spring-boot) application outlining usage of different MongoDB Data Models for atomic operations. 4 | The _Bookstore_ refers to and extends the [Model Data for Atomic Operations](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#model-data-for-atomic-operations) example. 5 | 6 | Use [Application Profiles](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html#boot-features-adding-active-profiles) to activate the different approaches. 7 | 8 | Profile | Description 9 | --- | --- 10 | sa | Synchronous Atomic Operations with denormalized Data Model 11 | stxn | Synchronous Multi Document Transactions using just the native MongoClient 12 | stx | Synchronous Spring managed Multi Document Transactions 13 | rtx | Reactive Multi Document Transactions 14 | rcs | Active this profile along with one of the transactional (stx, rtx) ones to subscribe to changes on the `order` collection. 15 | retry | Activate this profile to retry failed transactions via [Spring Retry](https://github.com/spring-projects/spring-retry). 16 | reset | Reset the initial set of collections and pre fill it with test data 17 | 18 | **Web Endpoints** 19 | 20 | URL | Sample | Description 21 | --- | --- | --- 22 | GET :8080/books | `http :8080/books` | List all books. 23 | GET :8080/book/{book} | `http :8080/book/bb4e114f` | A single Book. 24 | POST :8080/book/{book}/order?customer= | `http POST :8080/book/bb4e114f/order?customer=christoph` | Place an order for a book. 25 | 26 | ### Synchronous Atomic Operations with denormalized Data Model 27 | 28 | The denormalized Data Model keeps all required data in one place, the Document. Hence all updates of the one document are atomic. 29 | Each and every `Order` is tracked by `checkout` within the `Book` itself. 30 | 31 | ```json 32 | { 33 | "_id" : "bb4e114f", 34 | "title" : "The Painted Man", 35 | "author" : [ "Peter V. Brett" ], 36 | "published_date" : "2009-08-01", 37 | "pages" : 544, 38 | "language" : "English", 39 | "publisher_id" : "Harper Collins Publishers", 40 | "available" : 3, 41 | "checkout" : [ { "by": "cstrobl", "date" : "2018-08-27T10:11:59.853Z" } ] 42 | } 43 | 44 | ``` 45 | 46 | **Spring Profile:** sa 47 | **MongoDB Collections:** books 48 | **Components**: AtomicOrderService, SyncBookstoreHandler 49 | 50 | ### Synchronous Spring Managed Multi Document Transactions 51 | 52 | The transactional approach splits data between `Book` and `Order` whereas the `Order` references the `Book` via a `DBRef`. 53 | Still the number of available copies is kept within the `books` collection. 54 | 55 | ```json 56 | { 57 | "_id" : "bb4e114f", 58 | "title" : "The Painted Man", 59 | "author" : [ "Peter V. Brett" ], 60 | "published_date" : "2009-08-01", 61 | "pages" : 544, 62 | "language" : "English", 63 | "publisher_id" : "Harper Collins Publishers", 64 | "available" : 3 65 | } 66 | ``` 67 | 68 | ```json 69 | { 70 | "by" : "cstrobl", 71 | "date" : "2018-08-27T10:11:59.853Z", 72 | "books" : [ { "$ref" : "books", "$id" : "bb4e114f" } ] 73 | } 74 | ``` 75 | 76 | **Spring Profile:** stx 77 | **MongoDB Collections:** books, order 78 | **Components**: TransactionalOrderService, SyncBookstoreHandler 79 | 80 | ### Synchronous Multi Document Transactions with native MongoClient 81 | 82 | Just as in the sample above data is split between `Book` and `Order` whereas the `Order` references the `Book` via a `DBRef`. 83 | However, here we're using the native operations of `MongoClient` and `ClientSession` to run the transaction. 84 | 85 | **Spring Profile:** stxn 86 | **MongoDB Collections:** books, order 87 | **Components**: NativeMongoTransactionalOrderService, SyncBookstoreHandler 88 | 89 | ### Reactive Multi Document Transactions 90 | 91 | Just as the synchronous transactional approach data is split between `Book` and `Order`, this time using a reactive API 92 | for processing the checkout inside a transaction. 93 | 94 | ```json 95 | { 96 | "_id" : "bb4e114f", 97 | "title" : "The Painted Man", 98 | "author" : [ "Peter V. Brett" ], 99 | "published_date" : "2009-08-01", 100 | "pages" : 544, 101 | "language" : "English", 102 | "publisher_id" : "Harper Collins Publishers", 103 | "available" : 3 104 | } 105 | ``` 106 | 107 | ```json 108 | { 109 | "by" : "cstrobl", 110 | "date" : "2018-08-27T10:11:59.853Z", 111 | "books" : [ { "$ref" : "books", "$id" : "bb4e114f" } ] 112 | } 113 | ``` 114 | 115 | **Spring Profile:** rtx 116 | **MongoDB Collections:** books, order 117 | **Components**: ReactiveOrderService, ReactiveBookstoreHandler 118 | 119 | ### Retry Transactions 120 | 121 | It may happen that multiple transactions try to alter the very same document which leads to write conflicts and therefore 122 | the abortion of the transaction. 123 | 124 | This scenario can be provoked by: 125 | 126 | * Start the application 127 | * Open [Mongo Shell](https://docs.mongodb.com/manual/mongo/#the-mongo-shell) and execute 128 | ```bash 129 | rs0:PRIMARY> session = db.getMongo().startSession({ "mode" : "primary" }); 130 | rs0:PRIMARY> session.startTransaction(); 131 | rs0:PRIMARY> session.getDatabase("fantasy-bookstore").books.update({ "_id" : "f430cb49", "available" : { "$gt" : 0 } }, { "$inc" : { "available" : -1 } }); 132 | ``` 133 | * Call the order endpoint 134 | ```bash 135 | ~ $ http POST :8080/book/f430cb49/order?customer=cstrobl 136 | ``` 137 | * The Application will retry the operation for 3 times with 5 seconds delay in between. 138 | * Switch to Mongo Shell again and _commit_ the transaction within time to have the other one succeed as well. 139 | ```bash 140 | rs0:PRIMARY> session.commitTransaction(); 141 | ``` 142 | 143 | **Spring Profile:** stx,retry 144 | **MongoDB Collections:** books, order 145 | **Components**: TransactionalOrderService, SyncBookstoreHandler, RetryTemplate 146 | 147 | ## Requirements 148 | 149 | ### Java 150 | 151 | The application requires Java 8 (or better). 152 | 153 | ### MongoDB 154 | 155 | The Application requires [MongoDB 4.0](https://www.mongodb.com/download-center#production) or better running as [Replica Set](https://docs.mongodb.com/manual/tutorial/deploy-replica-set/#procedure). 156 | 157 | ### Project Lombok 158 | 159 | Some of the code uses [Project Lombok](https://projectlombok.org/). Make sure to have it. 160 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | --------------------------------------------------------------------------------