TestEvent
创建个实体,用于测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
@Data @ToString public class TestEvent extends ApplicationEvent implements Serializable {
private String name; private int age;
public TestEvent(Object source, String name, int age) { super(source); this.name = name; this.age = age; } }
|
Consumer
创建消息监听类,允许异步处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
@Component @EnableAsync public class Consumer implements ApplicationListener<TestEvent> {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
@Override @Async public void onApplicationEvent(TestEvent testEvent) { logger.info(" 接收到消息:" + testEvent); } }
|
Publisher
消息生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
@Component public class Publisher {
private static final Logger logger = LoggerFactory.getLogger(Publisher.class);
@Autowired private ApplicationEventPublisher publisher;
public void sendMsg() { logger.info(" 开始执行发送消息..."); publisher.publishEvent(new TestEvent(this, "muycode", 18)); } }
|
EventTest
创建测试类,测试消息收发
1 2 3 4 5 6 7 8 9 10 11 12
| @RunWith(SpringRunner.class) @SpringBootTest(classes = BsServiceApplication.class) public class EventTest {
@Autowired private Publisher publisher;
@Test public void test1(){ publisher.sendMsg(); } }
|
输出结果
通过结果我们可以看出,消息发送和接收都没问题,而且接收消息是采用不同于主线程 main 的子线程执行的。
1 2
| [main] com.muycode.bsservice.test.Publisher : 开始执行发送消息... [yTaskExecutor-1] com.muycode.bsservice.test.Consumer : 接收到消息:TestEvent(name=muycode, age=18)
|