avatar

目录
Spring构建消息模型

TestEvent

创建个实体,用于测试

java
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

创建消息监听类,允许异步处理

java
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

消息生产者

java
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

创建测试类,测试消息收发

java
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的子线程执行的。

Code
1
2
[           main] com.muycode.bsservice.test.Publisher     : 开始执行发送消息...
[yTaskExecutor-1] com.muycode.bsservice.test.Consumer : 接收到消息:TestEvent(name=muycode, age=18)
文章作者: 颜不喜
文章链接: https://www.muycode.cn/article/spring20200526.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 颜不喜
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论