TestEvent

创建个实体,用于测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Created with IntelliJ IDEA.
* DateTime: 2020/5/26 16:42
* 测试实体
*
* @author muycode
*/
@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
/**
* Created with IntelliJ IDEA.
* DateTime: 2020/5/26 16:42
* 消费者监听
*
* @author muycode
*/
@Component
@EnableAsync // 允许异步
public class Consumer implements ApplicationListener<TestEvent> {

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

/**
* 监听消费者消息
*
* @param testEvent
*/
@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
/**
* Created with IntelliJ IDEA.
* DateTime: 2020/5/26 16:42
* 生产者
*
* @author muycode
*/
@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)