gpt4 book ai didi

spring - 在 Spring 中使用 @Async 的 @EventListener

转载 作者:IT老高 更新时间:2023-10-28 13:50:39 25 4
gpt4 key购买 nike

尝试结合 @Async@EventListener 注释启用异步事件处理,但我仍然看到监听器正在发布线程中运行。

您可以在此处找到示例:

@SpringBootApplication
@EnableAsync
class AsyncEventListenerExample {

static final Logger logger = LoggerFactory.getLogger(AsyncEventListenerExample.class);

@Bean
TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}


static class MedicalRecordUpdatedEvent {

private String id;

public MedicalRecordUpdatedEvent(String id) {
this.id = id;
}

@Override
public String toString() {
return "MedicalRecordUpdatedEvent{" +
"id='" + id + '\'' +
'}';
}
}

@Component
static class Receiver {

@EventListener
void handleSync(MedicalRecordUpdatedEvent event) {
logger.info("thread '{}' handling '{}' event", Thread.currentThread(), event);
}

@Async
@EventListener
void handleAsync(MedicalRecordUpdatedEvent event) {
logger.info("thread '{}' handling '{}' event", Thread.currentThread(), event);
}

}

@Component
static class Producer {

private final ApplicationEventPublisher publisher;

public Producer(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}

public void create(String id) {
publisher.publishEvent(new MedicalRecordUpdatedEvent(id));
}

@Async
public void asynMethod() {
logger.info("running async method with thread '{}'", Thread.currentThread());
}
}

}

还有我的测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AsyncEventListenerExample.class)
public class AsyncEventListenerExampleTests {

@Autowired
Producer producer;

@Test
public void createEvent() throws InterruptedException {

producer.create("foo");

//producer.asynMethod();


// A chance to see the logging messages before the JVM exists.
Thread.sleep(2000);

}
}

但是在日志中我看到两个 @EventListener 都在 main 线程中运行。

2016-05-12 08:52:43.184  INFO 18671 --- [           main] c.z.e.async2.AsyncEventListenerExample   : thread 'Thread[main,5,main]' handling 'MedicalRecordUpdatedEvent{id='foo'}' event
2016-05-12 08:52:43.186 INFO 18671 --- [ main] c.z.e.async2.AsyncEventListenerExample : thread 'Thread[main,5,main]' handling 'MedicalRecordUpdatedEvent{id='foo'}' event

async 基础结构使用 @EnableAsync 和异步 TaskExecutor 进行初始化。

不知道我做错了什么。你能帮忙吗?

谢谢。

使用 Spring Boot 1.4.2.M2,所以 Spring 4.3.0.RC1

最佳答案

Spring Framework 4.3.0.RC1 中有一个回归导致您遇到的问题。如果您使用 SNAPSHOT,您的项目运行良好。

关于spring - 在 Spring 中使用 @Async 的 @EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com