嘗試啓用異步事件處理並結合@Async
和@EventListener
註釋,但我仍然看到偵聽器正在發佈線程中運行。@EventListener在@sync中的彈簧
,你可以在這裏找到的例子:
@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
S IN的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引導1.4.2.M2,所以Spring 4.3.0.RC1