activitemq整合spring

一.activmq的点对点模型

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.demo</groupId>
<artifactId>aq-test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <name>aq-test Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms-api</artifactId>
<version>1.1-rev-1</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.3.RELEASE</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency> </dependencies> <build>
<finalName>aq-test</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
ActiviteMq.class:(发送端)
package com.demo;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test; import javax.jms.*; public class ActiviteMq { @Test
public void testQueueProducer() throws JMSException {
//1.创建connectinfactory对象,需要指定服务的IP以及端口号
//brokerURL服务器的ip以及端口号
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://192.168.1.20:61616"
); //2.使用ConnectionFactory创建
Connection connection = connectionFactory.createConnection(); //3.开启链接,调用connection对象的start的方法
connection.start(); //4.使用connection对创建一个session对象
//[4.1] 第一参数:是否开启事务
//[4.2] 第二参数:当第一个参数为false的时候 才有意义 消息的应答模式
//1.自动应答2.手动应答 一般为自动 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //第五步:使用session对象创建一个destination对象(topic,queue) 此处创建一个queue对象
//参数:队列名称 Queue queue = session.createQueue("test-queue2"); //第六步 使用session创建一个producer对象
MessageProducer producer = session.createProducer(queue); //第七步 创建一个message对象 创建一个textmessage对象
TextMessage textMessage = session.createTextMessage("风风光光"); //第八步 使用producer对象发送消息
producer.send(textMessage); //第九步 关闭资源
producer.close();
session.close();
connection.close(); }
}
ReceiveMsf.class:(接收端)
package com.demo;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test; import javax.jms.*;
import java.io.IOException; public class ReceiveMsf { @Test
public void testQueueConsumer() throws JMSException, IOException { //1.创建connectinfactory对象,需要指定服务的IP以及端口号
//brokerURL服务器的ip以及端口号
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://192.168.1.20:61616"
); //2.使用ConnectionFactory创建
Connection connection = connectionFactory.createConnection(); //3.开启链接,调用connection对象的start的方法
connection.start(); //4.使用connection对创建一个session对象
//[4.1] 第一参数:是否开启事务
//[4.2] 第二参数:当第一个参数为false的时候 才有意义 消息的应答模式
//1.自动应答2.手动应答 一般为自动
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//第五步:使用session对象创建一个destination对象(topic,queue) 此处创建一个queue对象
//参数:队列名称 Queue queue = session.createQueue("test-queue2");
// 第六步:使用Session对象创建一个Consumer对象。
MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener(
new MessageListener() {
@Override
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String text = null;
//取消的内容
text = textMessage.getText();
//第八步 打印消息
System.out.println(text);
} catch (JMSException e) {
e.printStackTrace();
}
}
}
); //等待键盘输入 阻塞
System.in.read(); //第九步 关闭资源
consumer.close();
session.close();
connection.close();
}
}

二.activmq的发布订阅模型

TopicProducer.class
package com.demo.dingyue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test; import javax.jms.*; public class TopicProducer { @Test
public void testTopicProducer() throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://192.168.1.20:61616"
); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic("huaYuanBaoBao"); MessageProducer producer = session.createProducer(topic); TextMessage textMessage = session.createTextMessage("这个是发布订阅的"); producer.send(textMessage); producer.close();
session.close();
connection.close();
} }
TopicCustomer.class:
package com.demo.dingyue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test; import javax.jms.*;
import java.io.IOException; public class TopicCustomer { @Test
public void testTopicCustomer() throws JMSException, IOException {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://192.168.1.20:61616"
); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic("huaYuanBaoBao"); MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try{ TextMessage textMessage = (TextMessage) message;
String text = null;
//取出消息的内容
text= textMessage.getText(); System.out.println(text); }catch (Exception e){ e.printStackTrace();
}
}
}); System.out.println("消费端03");
System.in.read(); //关闭资源
connection.close();
consumer.close();
session.close(); }
}

和Spring整合:

spring-amq.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:component-scan base-package="com.demo.spring"/> <bean id="amqSenderService" class="com.demo.spring.AMQSenderServiceImpl">
<!--<bean id="user" class="com.demo.spring.User">-->
</bean> <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="trustAllPackages" value="true"/>
<property name="brokerURL">
<value>tcp://192.168.1.20:61616</value>
</property>
</bean>
</property>
<property name="maxConnections" value="100"></property>
</bean> <!--使用缓存可以提升效率-->
<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="jmsFactory"/>
<property name="sessionCacheSize" value="1"/>
</bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory"/>
<property name="messageConverter">
<bean class="org.springframework.jms.support.converter.SimpleMessageConverter"/>
</property>
</bean> <!--测试Queue,队列的名字是spring-queue-->
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
<!--<constructor-arg index="0" value="spring-queue"/>-->
<constructor-arg name="name" value="spring-queue"/>
</bean> <!--测试Topic-->
<bean id="destinationTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg index="0" value="spring-topic"/>
</bean> </beans>
AMQSenderServiceImpl:
package com.demo.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; @Service
public class AMQSenderServiceImpl { private static final Logger logger = LoggerFactory.getLogger(AMQSenderServiceImpl.class); @Resource(name = "jmsTemplate")
private JmsTemplate jmsTemplate; //目的地队列的明证,我们要向这个队列发送消息
@Resource(name = "destinationQueue")
private Destination destination; //向特定的队列发送消息
public void sendMsg(final User user) {
// final String msg = JSON.toJSONString(mqParamDto);
user.setEmail("javaceshi@aa.com");
user.setPassword("123456");
user.setPhone("123456");
user.setSex("M");
user.setUsername("javaceshi"); try {
logger.info("将要向队列{}发送的消息msg:{}", destination, user);
jmsTemplate.send(destination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
// return session.createObjectMessage(user);
return session.createTextMessage("2019/1/18message");
}
}); } catch (Exception ex) {
logger.error("向队列{}发送消息失败,消息为:{}", destination, user);
} }
}
AMQReceiverServiceImpl:
package com.demo.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; @Service
public class AMQReceiverServiceImpl {
private static final Logger logger = LoggerFactory.getLogger(AMQSenderServiceImpl.class); @Resource(name = "jmsTemplate")
private JmsTemplate jmsTemplate; //目的地队列的明证,我们要向这个队列接收消息
@Resource(name = "destinationQueue")
private Destination destination; //向特定的队列接收消息
public void receiverMsg(final User user) {
// try {
Object object = jmsTemplate.receive(destination);
User msg = (User) object;
System.out.println(msg); } catch (Exception ex) {
ex.printStackTrace();
} }
}

测试类:App

package com.demo.spring;

import com.demo.spring.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* 主发送类
*
*/
public class App
{
public static void main( String[] args )
{
final User user = new User();
user.setEmail("javaceshi@aa.com");
user.setPassword("123456");
user.setPhone("123456");
user.setSex("M");
user.setUsername("javaceshi"); ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-amq.xml");
AMQSenderServiceImpl sendService = (AMQSenderServiceImpl)context.getBean("amqSenderService");
sendService.sendMsg(user);
// sendService.send(user);
System.out.println("send successfully, please visit http://192.168.1.20:8161/admin to see it");
}
}

activitemq整合spring的更多相关文章

  1. 【Java EE 学习 81】【CXF框架】【CXF整合Spring】

    一.CXF简介 CXF是Apache公司下的项目,CXF=Celtix+Xfire:它支持soap1.1.soap1.2,而且能够和spring进行快速无缝整合. 另外jax-ws是Sun公司发布的一 ...

  2. Mybatis整合Spring

    根据官方的说法,在ibatis3,也就是Mybatis3问世之前,Spring3的开发工作就已经完成了,所以Spring3中还是没有对Mybatis3的支持.因此由Mybatis社区自己开发了一个My ...

  3. mybatis入门_一对多,多对多映射以及整合spring框架

    一.一对多映射. 1.1 一对多映射之根据多的一方关联查询一的一方 示例:查询出具体的订单信息,同时也查询出来订单的用户信息. 引入的订单表如下所示: 框选出来的为具体的外键. 订单的Pojo类如下所 ...

  4. 《SSM框架搭建》三.整合spring web

    感谢学习http://blog.csdn.net/zhshulin/article/details/37956105#,还是修改了spring到最新的版本和接口开发示例 根据前一篇日志,已经有了myb ...

  5. Maven 整合 spring profile实现多环境自动切换

    Maven 整合 spring profile实现多环境自动切换 时间:2014-03-19 15:32来源:Internet 作者:Internet 点击:525次 profile主要用在项目多环境 ...

  6. TinyFrame续篇:整合Spring IOC实现依赖注入

    上一篇主要讲解了如何搭建基于CodeFirst的ORM,并且在章节末我们获取了上下文对象的实例:BookContext.这节主要承接上一篇,来讲解如何整合Spring IOC容器实现控制反转,依赖注入 ...

  7. Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一 般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布 ...

  8. webservice 服务端例子+客户端例子+CXF整合spring服务端测试+生成wsdl文件 +cxf客户端代码自动生成

    首先到CXF官网及spring官网下载相关jar架包,这个不多说.webservice是干嘛用的也不多说. 入门例子 模拟新增一个用户,并返回新增结果,成功还是失败. 大概的目录如上,很简单. Res ...

  9. (转)Ehcache 整合Spring 使用页面、对象缓存

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

随机推荐

  1. 天天向上的力量 III

    描述 一年365天,以第1天的能力值为基数,记为1.0. 当好好学习时,能力值相比前一天提高N‰:当没有学习时,能力值相比前一天下降N‰. 每天努力或放任,一年下来的能力值相差多少呢?其中,N的取值范 ...

  2. 解决find命令报错: paths must precede expression(转)

    原文地址:https://www.cnblogs.com/peter1994/p/7297656.html 在一天早上,想在服务器 /tmp 目录清除一些pdf文件,大概一万多个文件,在执行命令的时候 ...

  3. Difference Among Mercedes Star Diagnostic Tool MB Star C3 C4 C5 C6

    Mercedes Star Diagnostic Tool newly update to MB Star C6.There are many star diangostic tool in the ...

  4. ActiveMQ_1学习

    学习资源 官方文档 http://activemq.apache.org/features.html 下载ActiveMQ选择版本 http://activemq.apache.org/overvie ...

  5. Linux下 刚安装完mysql 修改密码

    在Centos中安装MySQL后默认的是没有root密码的,默认的是回车, 那么为了方便需要修改密码. 没有密码为MYSQL加密码: mysql -uroot -p 回车 提示输入密码,为空回车 up ...

  6. C#字符串操作方法签名等

    class Program { /// <summary> /// C# 里Main方法不需要public,而且不允许有两个是Main(string[] args)[包括String[] ...

  7. PowerShell 命令行调试指引(转)

    How to manage a debugging session Before you start debugging, you must set one or more breakpoints. ...

  8. powershell ParameterSet解析

    自定义PowerShell函数,在设置参数的时候中,可以将参数设置为某些情况下可选,某些条件下又设置为必选. 示例代码从网站复制的. function Connect-Somewhere { [Cmd ...

  9. Python开发——2.基本数据类型之数字和字符串

    一.基本数据类型 基本数据类型包括:数字(int).字符串(str).列表(list).元祖(tuple).字典(dict).布尔值(bool). 查看输出数据的类型 a = "123&qu ...

  10. VP-UML系统建模工具研究

    一.基本信息 标题:VP-UML系统建模工具研究 时间:2014 出版源:软件工程师 领域分类:面向对象:CASE:UML:系统建模: 二.研究背景 问题定义:VP-UML系统建模的主要特点 难点:运 ...