Spring Boot 2 - метод, аннотированный @ asyn c, не называется асинхронным - PullRequest
0 голосов
/ 18 февраля 2020

Может быть, кто-то может мне помочь. В моем приложении SpringBoot 2 я хочу вызвать службу асинхронно . Я знаю, что есть много постов, посвященных этой проблеме, и я прочитал многие из них внимательно, но, к сожалению, я застрял.

Уязвимый сервис инициализируется в классе конфигурации (отмечены @Configuration и @EnableAsync). Служба реализует интерфейс, и интересный метод интерфейса, о котором я говорю, помечен @Async. Но, как я прочитал в другом посте, это не должно быть проблемой.

Инициализация компонента с помощью класса конфигурации:

@Configuration
@EnableAsync
public class GlobalConfiguration {


   @Bean
    public DocumentMimetypeDetectionService getPermittedMimetypes() throws IOException {
        DocumentMimetypeDetectionServiceImpl detectionService = new DocumentMimetypeDetectionServiceImpl();
        detectionService.setPermittedDocumentMimetypes(permittedDocumentMimetypes().getObjectType()
                .cast(permittedDocumentMimetypes().getObject()));
        return detectionService;
    }


   @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(1500);
        executor.setThreadNamePrefix("ServiceAsync-");
        executor.initialize();
        return executor;
    }    

}

Интерфейс DocumentMimetypeDetectionService:

public interface DocumentMimetypeDetectionService {

    @Async
    CompletableFuture<String> discoverDocumentMimetype(final InputStream aIs)
            throws DocumentMimetypeDetectionServiceException, IOException;
}

Я создал тест, чтобы проверить, вызывает ли служба асинхронный вызов. В дополнение к этому я включаю

Thread.sleep (1000)

log.debug ("текущий поток {}", Thread.currentThread (). GetId ());

в классе реализации службы (метод DiscoverDocumentMimetype) для проверки поведения asyn c.

Мой тестовый класс аннотирован @RunWith (SpringRunner.class) и @SpringBootTest.

А теперь вызов метода сервиса:

   private void checkFiles(List<FileInfo> files) 
            throws ExecutionException, InterruptedException, MasterindexValidationException {

        List<Mt> mtList = new ArrayList<>();
        files.forEach(f -> {
            try {
                Mt mt = new Mt(mimetypeDetectionService.discoverDocumentMimetype(f.getFileContainer().getContent()), f.getFileId());
                mtList.add(mt);

            } catch (DocumentMimetypeDetectionServiceException | InterruptedException | ExecutionException | IOException e) {
                throw new RuntimeException(String.format("error in verifying mimetype of file %s - detail: %s", f.getFileId(), e.getMessage()));
            }
        });

Что я наблюдал: вызов

Mt mt = new Mt (mimetypeDetectionService.discoverDocumentMimetype ( f.getFileContainer (). getContent ()), f.getFileId ());

не приводит к асинхронному поведению. Значит, служба обнаружения документов всегда застревает в спящем потоке, а Thread.Id всегда одинаков (вывод журнала).

Что я делаю не так? Любая помощь приветствуется. Большое спасибо заранее.

С уважением, Бодо

...