EnableReactiveMongo

This commit is contained in:
manalejandro 2018-11-25 02:19:23 +01:00
parent e6fe0cea8b
commit 8bda42b67e
10 changed files with 110 additions and 161 deletions

25
pom.xml
View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -15,7 +16,7 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version> <version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath /> <!-- lookup parent from repository -->
</parent> </parent>
<properties> <properties>
@ -38,20 +39,28 @@
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.webjars</groupId> <groupId>org.webjars</groupId>
<artifactId>jquery</artifactId> <artifactId>jquery</artifactId>
<version>3.3.1-1</version> <version>3.3.1-1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.webjars</groupId> <groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId> <artifactId>bootstrap</artifactId>
<version>4.1.3</version> <version>4.1.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId> <artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>

View File

@ -1,6 +1,9 @@
package com.manalejandro.mongodbcrud; package com.manalejandro.mongodbcrud;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -12,17 +15,16 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
import com.manalejandro.mongodbcrud.services.ItemService; import com.manalejandro.mongodbcrud.services.ItemService;
@SpringBootApplication @SpringBootApplication
@EnableAsync @EnableAsync
@EnableMongoRepositories(basePackages = { "com.manalejandro.mongodbcrud.repositories" }) @EnableReactiveMongoRepositories(basePackages = { "com.manalejandro.mongodbcrud.repositories" })
public class MongodbcrudApplication implements CommandLineRunner, AsyncConfigurer { public class MongodbcrudApplication implements CommandLineRunner, AsyncConfigurer {
private ItemService itemService; private ItemService itemService;
@ -38,12 +40,12 @@ public class MongodbcrudApplication implements CommandLineRunner, AsyncConfigure
SpringApplication.run(MongodbcrudApplication.class, args); SpringApplication.run(MongodbcrudApplication.class, args);
} }
public void run(String... args) throws Exception { public void run(String... args) throws InterruptedException, ExecutionException {
ArrayList<Item> items = new ArrayList<Item>(); final List<Item> items = new ArrayList<Item>();
for (int i = 1; i <= 10; i++) { for (int i = 1; i <= 10; i++) {
items.add(new Item("nombre_" + i, "apellido1_" + i, "apellido2_" + i)); items.add(new Item("nombre_" + i, "apellido1_" + i, "apellido2_" + i));
} }
if (this.itemService.saveAll(items).get()) { if (itemService.saveAll(items).block(Duration.ofSeconds(5))) {
this.logger.info("Datos de prueba cargados correctamente..."); this.logger.info("Datos de prueba cargados correctamente...");
} else { } else {
this.logger.error("Error: No se han podido cargar los datos"); this.logger.error("Error: No se han podido cargar los datos");
@ -61,8 +63,9 @@ public class MongodbcrudApplication implements CommandLineRunner, AsyncConfigure
return executor; return executor;
} }
@Bean
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler(); return new SimpleAsyncUncaughtExceptionHandler();
} }
} }

View File

@ -34,7 +34,7 @@ public class IndexController implements ErrorController {
public String index(final @ModelAttribute("indexForm") IndexForm indexForm, final Model model) public String index(final @ModelAttribute("indexForm") IndexForm indexForm, final Model model)
throws InterruptedException, ExecutionException { throws InterruptedException, ExecutionException {
IndexVO indexVO = new IndexVO(); IndexVO indexVO = new IndexVO();
indexVO.getListItem().addAll(itemService.getAll().get()); indexVO.getListItem().addAll(itemService.getAll());
model.addAttribute("indexVO", indexVO); model.addAttribute("indexVO", indexVO);
this.logger.info("GET index"); this.logger.info("GET index");
return "index"; return "index";
@ -49,15 +49,14 @@ public class IndexController implements ErrorController {
} }
@PostMapping("/new") @PostMapping("/new")
public String saveItem(final @ModelAttribute("indexForm") IndexForm indexForm) public String saveItem(final @ModelAttribute("indexForm") IndexForm indexForm) {
throws InterruptedException, ExecutionException {
Item item = new Item(); Item item = new Item();
item.setNombre(indexForm.getNombre()); item.setNombre(indexForm.getNombre());
item.setApellido1(indexForm.getApellido1()); item.setApellido1(indexForm.getApellido1());
item.setApellido2(indexForm.getApellido2()); item.setApellido2(indexForm.getApellido2());
this.logger.info("POST new item: " + item.getNombre() + " " + item.getApellido1() + " " + item.getApellido2()); this.logger.info("POST new item: " + item.getNombre() + " " + item.getApellido1() + " " + item.getApellido2());
if (!item.getNombre().isBlank() && !item.getApellido1().isBlank() && !item.getApellido2().isBlank()) { if (!item.getNombre().isBlank() && !item.getApellido1().isBlank() && !item.getApellido2().isBlank()) {
if (this.itemService.save(item).get()) { if (this.itemService.save(item).block()) {
return "redirect:/"; return "redirect:/";
} else { } else {
return "redirect:/error"; return "redirect:/error";
@ -68,10 +67,9 @@ public class IndexController implements ErrorController {
} }
@GetMapping("/{id}/edit") @GetMapping("/{id}/edit")
public String editItem(final @PathVariable String id, final Model model) public String editItem(final @PathVariable String id, final Model model) {
throws InterruptedException, ExecutionException {
IndexForm indexForm = new IndexForm(); IndexForm indexForm = new IndexForm();
Item item = itemService.getItem(id).get(); Item item = itemService.getItem(id).block();
this.logger.info("GET edit item: " + id); this.logger.info("GET edit item: " + id);
if (item != null) { if (item != null) {
indexForm.setId(item.getId()); indexForm.setId(item.getId());
@ -86,8 +84,7 @@ public class IndexController implements ErrorController {
} }
@PostMapping("/{id}/edit") @PostMapping("/{id}/edit")
public String saveEditItem(final @ModelAttribute("indexForm") IndexForm indexForm) public String saveEditItem(final @ModelAttribute("indexForm") IndexForm indexForm) {
throws InterruptedException, ExecutionException {
this.logger.info("POST edit item: " + indexForm.getId()); this.logger.info("POST edit item: " + indexForm.getId());
if (itemService.getItem(indexForm.getId()) != null && !indexForm.getNombre().isBlank() if (itemService.getItem(indexForm.getId()) != null && !indexForm.getNombre().isBlank()
&& !indexForm.getApellido1().isBlank() && !indexForm.getApellido2().isBlank()) { && !indexForm.getApellido1().isBlank() && !indexForm.getApellido2().isBlank()) {
@ -96,7 +93,7 @@ public class IndexController implements ErrorController {
item.setNombre(indexForm.getNombre()); item.setNombre(indexForm.getNombre());
item.setApellido1(indexForm.getApellido1()); item.setApellido1(indexForm.getApellido1());
item.setApellido2(indexForm.getApellido2()); item.setApellido2(indexForm.getApellido2());
if (this.itemService.save(item).get()) { if (this.itemService.save(item).block()) {
return "redirect:/"; return "redirect:/";
} else { } else {
return "redirect:/error"; return "redirect:/error";
@ -107,10 +104,10 @@ public class IndexController implements ErrorController {
} }
@GetMapping("/{id}/delete") @GetMapping("/{id}/delete")
public String deleteItem(final @PathVariable String id) throws InterruptedException, ExecutionException { public String deleteItem(final @PathVariable String id) {
this.logger.info("DELETE item: " + id); this.logger.info("DELETE item: " + id);
if (!id.isBlank()) { if (!id.isBlank()) {
Item item = this.itemService.getItem(id).get(); Item item = this.itemService.getItem(id).block();
if (item != null) { if (item != null) {
this.itemService.delete(item); this.itemService.delete(item);
return "redirect:/"; return "redirect:/";

View File

@ -1,5 +1,16 @@
package com.manalejandro.mongodbcrud.forms; package com.manalejandro.mongodbcrud.forms;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IndexForm { public class IndexForm {
private String id; private String id;
@ -7,35 +18,4 @@ public class IndexForm {
private String apellido1; private String apellido1;
private String apellido2; private String apellido2;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
} }

View File

@ -3,54 +3,30 @@ package com.manalejandro.mongodbcrud.model;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Document @Document
public class Item { public class Item {
@Id @Id
private String id; private String id;
@NonNull
private String nombre; private String nombre;
@NonNull
private String apellido1; private String apellido1;
@NonNull
private String apellido2; private String apellido2;
public Item() {
super();
}
public Item(String nombre, String apellido1, String apellido2) {
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
} }

View File

@ -1,10 +1,10 @@
package com.manalejandro.mongodbcrud.repositories; package com.manalejandro.mongodbcrud.repositories;
import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
@Repository @Repository
public interface ItemRepository extends MongoRepository<Item, String> { public interface ItemRepository extends ReactiveMongoRepository<Item, String> {
} }

View File

@ -1,19 +1,21 @@
package com.manalejandro.mongodbcrud.services; package com.manalejandro.mongodbcrud.services;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
import reactor.core.publisher.Mono;
public interface ItemService { public interface ItemService {
public CompletableFuture<Item> getItem(String id); public Mono<Item> getItem(String id);
public CompletableFuture<List<Item>> getAll(); public List<Item> getAll() throws InterruptedException, ExecutionException;
public CompletableFuture<Boolean> save(Item item); public Mono<Boolean> save(Item item);
public Mono<Boolean> saveAll(List<Item> items);
public CompletableFuture<Boolean> saveAll(List<Item> items);
public void delete(Item item); public void delete(Item item);
} }

View File

@ -1,7 +1,9 @@
package com.manalejandro.mongodbcrud.services; package com.manalejandro.mongodbcrud.services;
import java.time.Duration;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@ -10,6 +12,8 @@ import org.springframework.stereotype.Service;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
import com.manalejandro.mongodbcrud.repositories.ItemRepository; import com.manalejandro.mongodbcrud.repositories.ItemRepository;
import reactor.core.publisher.Mono;
@Service @Service
public class ItemServiceImpl implements ItemService { public class ItemServiceImpl implements ItemService {
@ -21,29 +25,34 @@ public class ItemServiceImpl implements ItemService {
} }
@Async @Async
public CompletableFuture<List<Item>> getAll() { public List<Item> getAll() throws InterruptedException, ExecutionException {
return CompletableFuture.completedFuture(this.itemRepository.findAll()); return CompletableFuture
.completedFuture(this.itemRepository.findAll().collectList().block(Duration.ofSeconds(5))).get();
} }
@Async @Async
public CompletableFuture<Item> getItem(String id) { public Mono<Item> getItem(String id) {
return this.itemRepository.findById(id).isPresent() return this.itemRepository.findById(id).block(Duration.ofSeconds(5)) != null ? Mono.fromFuture(
? CompletableFuture.completedFuture(this.itemRepository.findById(id).get()) CompletableFuture.completedFuture(this.itemRepository.findById(id).block(Duration.ofSeconds(5))))
: null; : null;
} }
@Async @Async
public CompletableFuture<Boolean> save(Item item) { public Mono<Boolean> save(Item item) {
return this.itemRepository.save(item) != null ? CompletableFuture.completedFuture(Boolean.TRUE) : CompletableFuture.completedFuture(Boolean.FALSE); return this.itemRepository.save(item).block(Duration.ofSeconds(5)) != null
? Mono.fromFuture(CompletableFuture.completedFuture(Boolean.TRUE))
: Mono.fromFuture(CompletableFuture.completedFuture(Boolean.FALSE));
} }
@Async @Async
public CompletableFuture<Boolean> saveAll(List<Item> items) { public Mono<Boolean> saveAll(List<Item> items) {
return this.itemRepository.saveAll(items) != null ? CompletableFuture.completedFuture(Boolean.TRUE) : CompletableFuture.completedFuture(Boolean.FALSE); return this.itemRepository.saveAll(items).collectList().block(Duration.ofSeconds(5)) != null
? Mono.fromFuture(CompletableFuture.completedFuture(Boolean.TRUE))
: Mono.fromFuture(CompletableFuture.completedFuture(Boolean.FALSE));
} }
@Async @Async
public void delete(Item item) { public void delete(Item item) {
this.itemRepository.delete(item); this.itemRepository.delete(item).block(Duration.ofSeconds(5));
} }
} }

View File

@ -5,52 +5,23 @@ import java.util.List;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IndexVO { public class IndexVO {
private List<Item> listItem = new ArrayList<Item>(); private final List<Item> listItem = new ArrayList<Item>();
private String id; private String id;
private String nombre; private String nombre;
private String apellido1; private String apellido1;
private String apellido2; private String apellido2;
public List<Item> getListItem() {
return listItem;
}
public void setListItem(List<Item> listItem) {
this.listItem = listItem;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
} }

View File

@ -1,3 +1,5 @@
server.servlet.context-path=/mongodbcrud server.servlet.context-path=/mongodbcrud
server.port=3117 server.port=3117
spring.thymeleaf.cache=false spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test