实现消息队列的两种方式
Apache ActiveMQ官方实例发送消息
直接在Apache官网http://activemq.apache.org/download-archives.html下载ActiveMQ源码
下载解压后拿到java代码实例
然后倒入IDE
如下:
请认真阅读readme.md文件,大致意思就是把项目打成两个jar包,然后启动服务,然后同时运行打的两个jar包,然后就能看到具体的调用信息。打jar包时直接利用maven打就行了,不用修改代码。
启动服务:
利用Spring消息模板发送消息
Spirng对Apache ActiveMQ提供了很好的支持
生成者代码:
package com.jms.service.impl;import com.jms.service.ProducerService;import org.springframework.jms.core.JmsTemplate;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.jms.Destination;/** * 发送消息 */@Servicepublic class ProducerServiceImpl implements ProducerService { @Resource private JmsTemplate jmsTemplate; public void sendMessage(Destination destination, String msg) { System.out.println("向队列"+destination+"发送消息"); jmsTemplate.convertAndSend(destination,msg); } public void sendMessage(String msg) { System.out.println("向队列"+jmsTemplate.getDefaultDestination().toString()+"发送消息"); jmsTemplate.convertAndSend(msg); }}消费者代码:
package com.jms.service.impl;import com.jms.service.CustomerService;import org.springframework.jms.core.JmsTemplate;import org.springframework.stereotype.Service;import javax.annotation.Resource;import javax.jms.Destination;import javax.jms.JMSException;import javax.jms.TextMessage;@Servicepublic class CustomerServiceImpl implements CustomerService { @Resource private JmsTemplate jmsTemplate; /** * 接收消息 * @param destination */ public void receive(Destination destination) { TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination); try { System.out.println("从队列》"+destination.toString()+"成功获取消息》"+textMessage.getText()); } catch (JMSException e) { e.printStackTrace(); } }}Spring配置代码
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http:///wahnn/SpringJMS以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。