21xrx.com
2025-04-21 20:19:15 Monday
文章检索 我的文章 写文章
Java消息通知技术解析
2023-06-15 20:18:14 深夜i     11     0

Java通知技术是一种将应用程序信息或状态改变通知给其它程序或用户的重要技术手段,对于实时性要求较高的业务场景尤为适用,比如网络通信、即时通讯、订单管理等。本文将从消息通知的基本原理、Java消息通知框架和代码案例等多个方面来详细介绍Java消息通知的实现方式和技术应用。

一、消息通知的原理

基于观察者模式(Observer Pattern)实现,该模式定义了一种一对多的依赖关系,即一个对象(主题)的状态改变会对其依赖的所有对象(观察者)通知。在Java中,主题(Subject)持有观察者(Observer)的引用列表,当主题状态改变后,会遍历并调用所有观察者的更新方法。

二、Java消息通知框架

1. JMS(Java Message Service)是JavaEE的标准消息中间件,提供了一种面向消息的应用程序编程模型。JMS支持消息发布-订阅(Pub/Sub)和点对点(P2P)两种消息传递方式,可提供异步解耦应用的效果。

2. Spring框架的JMS支持,可将JMS与Spring集成,更加方便地满足应用程序中消息通知的需求。

3. Kafka是一个高性能、高可扩展性的分布式流处理平台,通过分区、复制和容错机制确保数据安全。Kafka支持多种数据格式,适合大数据量、高并发、实时性要求较高的场景。

三、Java消息通知案例

代码实现采用Spring Boot、ActiveMQ和Thymeleaf技术栈,实现一个简单的消息通知应用。具体实现过程包括:

1. 编写ActiveMQ配置文件,定义消息队列和主题。

2. 定义消息发送和接收服务,封装了消息发送和接收的逻辑。

3. 编写Controller类,处理消息通知的请求。

4. 编写页面模板,展示消息通知的内容。

相关代码和效果图如下:

1. 配置文件application.yml

spring:
 activemq:
  broker-url: tcp://localhost:61616
  user: admin
  password: admin

2. 消息发送和接收服务

@Service
public class ActiveMQService {
  @Autowired
  private JmsMessagingTemplate jmsMessagingTemplate;
  public void sendQueueMessage(String destination, String message) {
    jmsMessagingTemplate.convertAndSend(destination, message);
  }
  public void sendTopicMessage(String destination, String message) {
    jmsMessagingTemplate.convertAndSend(destination, message);
  }
  public String receiveQueueMessage(String destination) {
    return (String) jmsMessagingTemplate.receive(destination).getPayload();
  }
  public String receiveTopicMessage(String destination) {
    return (String) jmsMessagingTemplate.receive(destination).getPayload();
  }
}

3. Controller类

@Controller
public class NotifyController {
  @Autowired
  private ActiveMQService activeMQService;
  @GetMapping("/sendQueue")
  public String sendQueueMessage(@RequestParam String message) {
    activeMQService.sendQueueMessage("queue.notify", message);
    return "notify";
  }
  @GetMapping("/sendTopic")
  public String sendTopicMessage(@RequestParam String message) {
    activeMQService.sendTopicMessage("topic.notify", message);
    return "notify";
  }
  @GetMapping("/receiveQueue")
  public String receiveQueueMessage(Model model) {
    String message = activeMQService.receiveQueueMessage("queue.notify");
    model.addAttribute("message", message);
    return "notify_result";
  }
  @GetMapping("/receiveTopic")
  public String receiveTopicMessage(Model model) {
    String message = activeMQService.receiveTopicMessage("topic.notify");
    model.addAttribute("message", message);
    return "notify_result";
  }
}

4. 页面模板

消息通知
  
消息通知
  

     
     发送Queue消息
   

  

     
     发送Topic消息
   

  接收Queue消息
  接收Topic消息

效果图:

![notify.png](https://cdn.nlark.com/yuque/0/2021/png/19053835/1629637323045-44067766-9068-4329-a7d2-7b45e2ca99aa.png)

四、关键词

1. 消息通知

2. Java

3. 观察者模式

  
  

评论区