ActiveMQ整合Spring框架

网友投稿 259 2022-09-24

ActiveMQ整合Spring框架

前面文章介绍了ActiveMQ的相关内容,本文介绍ActiveMQ和Spring的整合开发

整合Spring框架

1.相关jar包

activemq-all-5.9.0.jaraopalliance-1.0.jarcommons-logging-1.2.jarspring-aop-4.1.6.RELEASE.jarspring-beans-4.1.6.RELEASE.jarspring-context-4.1.6.RELEASE.jarspring-core-4.1.6.RELEASE.jarspring-expression-4.1.6.RELEASE.jarspring-jms-4.1.6.RELEASE.jarspring-messaging-4.1.6.RELEASE.jarspring-tx-4.1.6.RELEASE.jarspring-web-4.1.6.RELEASE.jarxbean-spring-4.5.jar

相关maven坐标

org.apache.activemq activemq-all 5.9.0 org.apache.xbean xbean-spring 4.5 org.springframework spring-jms 4.1.6.RELEASE org.springframework spring-context 4.1.6.RELEASE

2.定义消费者

package com.dpb.consumer;import javax.jms.Message;import javax.jms.MessageListener;import javax.jms.ObjectMessage;import com.dpb.bean.Order;/** * ActiveMQ Consumer消费者 * @author dengp * */public class OrderConsumer implements MessageListener{ @Override public void onMessage(Message message) { try{ ObjectMessage objectMassage = (ObjectMessage) message; Order order = (Order) objectMassage.getObject(); System.out.println("the order is : " + order); }catch(Exception e){ e.printStackTrace(); } }}

3.定义生产者

package com.dpb.producer;import javax.jms.JMSException;import javax.jms.Message;import javax.jms.ObjectMessage;import javax.jms.Session;import org.springframework.jms.core.JmsTemplate;import org.springframework.jms.core.MessageCreator;import com.dpb.bean.Order;/** * ActiveMQ producer 生产者 * @author dengp * */public class OrderProducer { private JmsTemplate template; public JmsTemplate getTemplate() { return template; } public void setTemplate(JmsTemplate template) { this.template = template; } /** * 生产者发送消息 * @param destinationName 目的地名称 * @param order 需要发送的订单数据 */ public void sendOrder(String destinationName, Order order){ try{ template.send(destinationName, new MessageCreator() { /** * 通过模板模式暴露的方法设置发送的信息 */ @Override public Message createMessage(Session session) throws JMSException { ObjectMessage objectMessage = session.createObjectMessage(order); return objectMessage; } }); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("send order to MQ server error!!"); } }}

4.Spring配置文件整合ActiveMQ

5.测试

public class Test { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); OrderProducer pro = ac.getBean("orderProducer",OrderProducer.class); Order order = new Order(); order.setId("101"); order.setNick("波波烤鸭"); order.setPrice(10000L); order.setCreateTime(new Date()); pro.sendOrder("test-spring", order); }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:TCP基础(2)
下一篇:科技狐:电视台曝光了!售价3980,成本价80,你被坑过吗?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~