EnableAsync

This commit is contained in:
manalejandro 2018-11-24 21:23:55 +01:00
parent 743f9c6fcc
commit e6fe0cea8b
4 changed files with 67 additions and 27 deletions

View File

@ -1,21 +1,29 @@
package com.manalejandro.mongodbcrud; package com.manalejandro.mongodbcrud;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.Executor;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; 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.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
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
@EnableMongoRepositories(basePackages = { "com.manalejandro.mongodbcrud.repositories" }) @EnableMongoRepositories(basePackages = { "com.manalejandro.mongodbcrud.repositories" })
public class MongodbcrudApplication implements CommandLineRunner { public class MongodbcrudApplication implements CommandLineRunner, AsyncConfigurer {
private ItemService itemService; private ItemService itemService;
private Logger logger; private Logger logger;
@ -35,10 +43,26 @@ public class MongodbcrudApplication implements CommandLineRunner {
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)) { if (this.itemService.saveAll(items).get()) {
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");
} }
} }
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("Thread-");
executor.initialize();
return executor;
}
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
} }

View File

@ -1,5 +1,7 @@
package com.manalejandro.mongodbcrud.controllers; package com.manalejandro.mongodbcrud.controllers;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -28,10 +30,11 @@ public class IndexController implements ErrorController {
this.logger = LoggerFactory.getLogger(this.getClass()); this.logger = LoggerFactory.getLogger(this.getClass());
} }
@GetMapping({"/", "/index"}) @GetMapping({ "/", "/index" })
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 {
IndexVO indexVO = new IndexVO(); IndexVO indexVO = new IndexVO();
indexVO.getListItem().addAll(itemService.getAll()); indexVO.getListItem().addAll(itemService.getAll().get());
model.addAttribute("indexVO", indexVO); model.addAttribute("indexVO", indexVO);
this.logger.info("GET index"); this.logger.info("GET index");
return "index"; return "index";
@ -46,14 +49,15 @@ 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)) { if (this.itemService.save(item).get()) {
return "redirect:/"; return "redirect:/";
} else { } else {
return "redirect:/error"; return "redirect:/error";
@ -64,9 +68,10 @@ 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); Item item = itemService.getItem(id).get();
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());
@ -81,7 +86,8 @@ 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()) {
@ -90,7 +96,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)) { if (this.itemService.save(item).get()) {
return "redirect:/"; return "redirect:/";
} else { } else {
return "redirect:/error"; return "redirect:/error";
@ -101,10 +107,10 @@ public class IndexController implements ErrorController {
} }
@GetMapping("/{id}/delete") @GetMapping("/{id}/delete")
public String deleteItem(final @PathVariable String id) { public String deleteItem(final @PathVariable String id) throws InterruptedException, ExecutionException {
this.logger.info("DELETE item: " + id); this.logger.info("DELETE item: " + id);
if (!id.isBlank()) { if (!id.isBlank()) {
Item item = this.itemService.getItem(id); Item item = this.itemService.getItem(id).get();
if (item != null) { if (item != null) {
this.itemService.delete(item); this.itemService.delete(item);
return "redirect:/"; return "redirect:/";

View File

@ -1,18 +1,19 @@
package com.manalejandro.mongodbcrud.services; package com.manalejandro.mongodbcrud.services;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
public interface ItemService { public interface ItemService {
public Item getItem(String id); public CompletableFuture<Item> getItem(String id);
public List<Item> getAll(); public CompletableFuture<List<Item>> getAll();
public boolean save(Item item); public CompletableFuture<Boolean> save(Item item);
public 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,8 +1,10 @@
package com.manalejandro.mongodbcrud.services; package com.manalejandro.mongodbcrud.services;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.manalejandro.mongodbcrud.model.Item; import com.manalejandro.mongodbcrud.model.Item;
@ -18,22 +20,29 @@ public class ItemServiceImpl implements ItemService {
this.itemRepository = itemRepository; this.itemRepository = itemRepository;
} }
public List<Item> getAll() { @Async
return this.itemRepository.findAll(); public CompletableFuture<List<Item>> getAll() {
return CompletableFuture.completedFuture(this.itemRepository.findAll());
} }
public Item getItem(String id) { @Async
return this.itemRepository.findById(id).isPresent() ? this.itemRepository.findById(id).get() : null; public CompletableFuture<Item> getItem(String id) {
return this.itemRepository.findById(id).isPresent()
? CompletableFuture.completedFuture(this.itemRepository.findById(id).get())
: null;
} }
public boolean save(Item item) { @Async
return this.itemRepository.save(item) != null ? Boolean.TRUE : Boolean.FALSE; public CompletableFuture<Boolean> save(Item item) {
return this.itemRepository.save(item) != null ? CompletableFuture.completedFuture(Boolean.TRUE) : CompletableFuture.completedFuture(Boolean.FALSE);
} }
public boolean saveAll(List<Item> items) { @Async
return this.itemRepository.saveAll(items) != null ? Boolean.TRUE : Boolean.FALSE; public CompletableFuture<Boolean> saveAll(List<Item> items) {
return this.itemRepository.saveAll(items) != null ? CompletableFuture.completedFuture(Boolean.TRUE) : CompletableFuture.completedFuture(Boolean.FALSE);
} }
@Async
public void delete(Item item) { public void delete(Item item) {
this.itemRepository.delete(item); this.itemRepository.delete(item);
} }