activemq

ActiveMQ
一、 ActiveMQ简介
1 什么是ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。
2 什么是消息
“消息”是在两台计算机间传送的数据单位。消息可以非常简单,例如只包含文本字符串;也可以更复杂,可能包含嵌入对象。
3 什么是队列

4 什么是消息队列
“消息队列”是在消息的传输过程中保存消息的容器。
5 常用消息服务应用
5.1 ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。
5.2 RabbitMQ
RabbitMQ是一个在AMQP基础上完成的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。开发语言为Erlang。
5.3 RocketMQ
由阿里巴巴定义开发的一套消息队列应用服务。
二、 消息服务的应用场景
消息队列的主要特点是异步处理,主要目的是减少请求响应时间和解耦。所以主要的使用场景就是将比较耗时而且不需要即时(同步)返回结果的操作作为消息放入消息队列。同时由于使用了消息队列,只要保证消息格式不变,消息的发送方和接收方并不需要彼此联系,也不需要受对方的影响,即解耦和。

5.1 异步处理

5.2 应用的解耦
5.2.1 订单处理
生成订单流程:
1)在购物车中点击结算
2)完成支付
3)创建订单
4)调用库存系统
订单完成后,订单系统并不去直接调用库存系统,而是发送消息到消息中间件,写入一个订单信息。库存系统自己去消息中间件上去获取,然后做发货处理,并更新库存,这样能够实现互联网型应用追求的快这一个属性。而库存系统读取订单后库存应用这个操作也是非常快的,所以有消息中间件对解耦来说也是一个不错的方向。

5.3 流量的削峰
5.3.1 秒杀功能
秒杀流程:
1)用户点击秒杀
2)发送请求到秒杀应用
3)在请求秒杀应用之前将请求放入到消息队列
4)秒杀应用从消息队列中获取请求并处理。
比如,系统举行秒杀活动,热门商品。流量蜂拥而至 100件商品,10万人挤进来怎么办?10万秒杀的操作,放入消息队列。秒杀应用处理消息队列中的10万个请求中的前100个,其他的打回,通知失败。流量峰值控制在消息队列处,秒杀应用不会瞬间被怼死.

三、 JMS
1 什么是JMS
JMS(Java Messaging Service)是Java平台上有关面向消息中间件的技术规范,它便于消息系统中的Java应用程序进行消息交换,并且通过提供标准的产生、发送、接收消息的接口,简化企业应用的开发。
2 JMS模型
2.1 点对点模型(Point To Point)
生产者发送一条消息到queue,只有一个消费者能收到。

2.2 发布订阅模型(Publish/Subscribe)
发布者发送到topic的消息,只有订阅了topic的订阅者才会收到消息。

四、 ActiveMQ安装
1 下载资源
ActiveMQ官网: http://activemq.apache.org

1.1 版本说明
ActiveMQ5.10.x以上版本必须使用JDK1.8才能正常使用。
ActiveMQ5.9.x及以下版本使用JDK1.7即可正常使用。
2 上传至Linux服务器

3 解压安装文件
tar -zxf apache-activemq-5.9.0-bin.tar.gz
4 检查权限
ls -al apache-activemq-5.9.0/bin
如果权限不足,则无法执行,需要修改文件权限:
chmod 755 activemq
5 复制应用至本地目录
cp -r apache-activemq-5.9.0 /usr/local/activemq
6 启动ActiveMQ
/usr/local/activemq/bin/activemq start
7 测试ActiveMQ
7.1 检查进程
ps aux | grep activemq
见到下述内容即代表启动成功

7.2 管理界面
使用浏览器访问ActiveMQ管理应用, 地址如下:
http://ip:8161/admin/
用户名: admin
密码: admin
ActiveMQ使用的是jetty提供HTTP服务.启动稍慢,建议短暂等待再访问测试.
见到如下界面代表服务启动成功

7.3 修改访问端口
修改ActiveMQ配置文件: /usr/local/activemq/conf/jetty.xml

配置文件修改完毕,保存并重新启动ActiveMQ服务。
7.4 修改用户名和密码
修改conf/users.properties配置文件.内容为: 用户名=密码
保存并重启ActiveMQ服务即可.
8 重启ActiveMQ
/usr/local/activemq/bin/activemq restart
9 关闭ActiveMQ
/usr/local/activemq/bin/activemq stop
10 配置文件activemq.xml
配置文件中,配置的是ActiveMQ的核心配置信息. 是提供服务时使用的配置. 可以修改启动的访问端口. 即java编程中访问ActiveMQ的访问端口.
默认端口为61616.
使用协议是: tcp协议.
修改端口后, 保存并重启ActiveMQ服务即可.
11 ActiveMQ目录介绍
从它的目录来说,还是很简单的:

  • bin存放的是脚本文件
  • conf存放的是基本配置文件
  • data存放的是日志文件
  • docs存放的是说明文档
  • examples存放的是简单的实例
  • lib存放的是activemq所需jar包
  • webapps用于存放项目的目录

五、 ActiveMQ术语
1 Destination
目的地,JMS Provider(消息中间件)负责维护,用于对Message进行管理的对象。MessageProducer需要指定Destination才能发送消息,MessageReceiver需要指定Destination才能接收消息。
2 Producer
消息生成者,负责发送Message到目的地。
3 Consumer | Receiver
消息消费者,负责从目的地中消费【处理|监听|订阅】Message。
4 Message
消息,消息封装一次通信的内容。

六、 ActiveMQ应用
1 ActiveMQ常用API简介
下述API都是接口类型,由定义在javax.jms包中.
是JMS标准接口定义.
1.1 ActiveMQConnectionFactory
链接工厂, 用于创建链接的工厂类型.
1.2 Connection
链接. 用于建立访问ActiveMQ连接的类型, 由链接工厂创建.
1.3 Session
会话, 一次持久有效有状态的访问. 由链接创建.
1.4 Destination & Queue
目的地, 用于描述本次访问ActiveMQ的消息访问目的地. 即ActiveMQ服务中的具体队列. 由会话创建.
interface Queue extends Destination
1.5 MessageProducer
消息生成者, 在一次有效会话中, 用于发送消息给ActiveMQ服务的工具. 由会话创建.
1.6 MessageConsumer
消息消费者【消息订阅者,消息处理者】, 在一次有效会话中, 用于从ActiveMQ服务中获取消息的工具. 由会话创建.
1.7 Message
消息, 通过消息生成者向ActiveMQ服务发送消息时使用的数据载体对象或消息消费者从ActiveMQ服务中获取消息时使用的数据载体对象. 是所有消息【文本消息,对象消息等】具体类型的顶级接口. 可以通过会话创建或通过会话从ActiveMQ服务中获取.
2 JMS-HelloWorld
2.1 处理文本消息
2.1.1 创建消息生产者
2.1.1.1 修改POM文件添加ActiveMQ坐标

4.0.0
com.bjsxt
mq-producer
0.0.1-SNAPSHOT

org.apache.activemq activemq-all 5.15.10

2.1.1.2 编写消息的生产者
public class HelloWorldProducer {
public static void main(String[] args) {
HelloWorldProducer producer = new HelloWorldProducer();
producer.sendHelloWorld(“Hello bjsxt”);
}

public void sendHelloWorld(String msg){
    //定义链接工厂
    ActiveMQConnectionFactory

connectionFactory = null;
//定义链接对象
Connection connection = null;
//定义会话
Session session = null;
//目的地
Destination destination = null;
//定义消息的发送者
MessageProducer producer = null;
//定义消息
Message message = null;
try{
/**
* userName:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
* password:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
* brokerURL:访问ActiveMQ服务的路径地址。路径结构为:协议名://主机地址:端口号
*/
connectionFactory = new ActiveMQConnectionFactory(“admin”, “admin”, “tcp://192.168.70.151:61616”);

        //创建连接对象
        connection = connectionFactory.createConnection();

        //启动连接
        connection.start();

        /**
         * transacted:是否使用事务 可选值为:true|false
         *            true:使用事务 当设置次变量值。Session.SESSION_TRANSACTED
         *            false:不适用事务,设置次变量 则acknowledgeMode参数必须设置
         * acknowledgeMode:
         * Session.AUTO_ACKNOWLEDGE:自动消息确认机制
         * Session.CLIENT_ACKNOWLEDGE:客户端确认机制
         * Session.DUPS_OK_ACKNOWLEDGE:有副本的客户端确认消息机制
         */
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地,目的地名称即队列的名称。消息的消费者需要通过此名称访问对应的队列
        destination = session.createQueue("helloworld");
        //创建消息的生产者
        producer = session.createProducer(destination);
        //创建消息对象
        message = session.createTextMessage(msg);
        //发送消息
        producer.send(message);
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        //回收消息发送者资源
        if(producer != null){
            try {
                producer.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(session != null){
            try {
                session.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

}

2.1.2 创建消息消费者
2.1.2.1 修改POM文件添加ActiveMQ坐标

4.0.0
com.bjsxt
mq-consumer
0.0.1-SNAPSHOT



org.apache.activemq
activemq-all
5.15.10



2.1.2.2 编写消息的消费者
public class HelloWorldConsumer {
public static void main(String[] args) {
HelloWorldConsumer consumer = new HelloWorldConsumer();
consumer.readHelloWorld();
}
public void readHelloWorld(){
ActiveMQConnectionFactory factory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
Message message = null;
try{
factory = new ActiveMQConnectionFactory(“admin”,“admin”,“tcp://192.168.40.138:61616”);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(“helloworld”);
consumer = session.createConsumer(destination);
message = consumer.receive();
String text = ((TextMessage) message).getText();
System.out.println(text);

    }catch(Exception e){
        e.printStackTrace();
    }
    finally {
        try{
            consumer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            session.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

}

2.2 处理对象消息
2.2.1 定义消息对象
public class Users implements Serializable {
private Integer userid;
private String username;
private String usersex;

public Integer getUserid() {
    return userid;
}

public void setUserid(Integer userid) {
    this.userid = userid;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getUsersex() {
    return usersex;
}

public void setUsersex(String usersex) {
    this.usersex = usersex;
}

}

2.2.2 创建生产者
public class HelloWorldProducer2 {
public static void main(String[] args) {
HelloWorldProducer2 producer = new HelloWorldProducer2();
Users user = new Users();
user.setUsername(“Oldlu”);
user.setUserid(1);
user.setUsersex(“男”);
producer.sendHelloWorld(user);
}

public void sendHelloWorld(Users users){
    //定义链接工厂
     ActiveMQConnectionFactory connectionFactory = null;
    //定义链接对象
    Connection connection = null;
    //定义会话
    Session session = null;
    //目的地
    Destination destination = null;
    //定义消息的发送者
    MessageProducer producer = null;
    //定义消息
    Message message = null;
    try{
        /**
         * userName:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * password:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * brokerURL:访问ActiveMQ服务的路径地址。路径结构为:协议名://主机地址:端口号
         */
        connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.40.138:61616");

        //创建连接对象
        connection = connectionFactory.createConnection();

        //启动连接
        connection.start();

        /**
         * transacted:是否使用事务 可选值为:true|false
         *            true:使用事务 当设置次变量值。Session.SESSION_TRANSACTED
         *            false:不适用事务,设置次变量 则acknowledgeMode参数必须设置
         * acknowledgeMode:
         * Session.AUTO_ACKNOWLEDGE:自动消息确认机制
         * Session.CLIENT_ACKNOWLEDGE:客户端确认机制
         * Session.DUPS_OK_ACKNOWLEDGE:有副本的客户端确认消息机制
         */
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地,目的地名称即队列的名称。消息的消费者需要通过此名称访问对应的队列
        destination = session.createQueue("my-user");

        //创建消息的生产者
        producer = session.createProducer(destination);

        //创建消息对象
        message = session.createObjectMessage();

        //发送消息
        producer.send(message);

    }catch(Exception e){
        e.printStackTrace();
    }finally{

        //回收消息发送者资源
        if(producer != null){
            try {
                producer.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(session != null){
            try {
                session.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

}

2.2.3 定义消息消费者
public class HelloWorldConsumer2 {
public static void main(String[] args) {
HelloWorldConsumer2 consumer = new HelloWorldConsumer2();
consumer.readHelloWorld();
}
public void readHelloWorld(){
ActiveMQConnectionFactory factory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
Message message = null;
try{
factory = new ActiveMQConnectionFactory(“admin”,“admin”,“tcp://192.168.40.138:61616”);
//在activemq5.12以上的版本中需要调用该方法
factory.setTrustAllPackages(true);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(“my-user”);
consumer = session.createConsumer(destination);
message = consumer.receive();
ObjectMessage om = (ObjectMessage)message;
Users users = (Users) om.getObject();
System.out.println(users);

    }catch(Exception e){
        e.printStackTrace();
    }
    finally {
        try{
            consumer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            session.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

}

3 JMS - 实现队列服务监听
队列服务监听使用的观察者设计模式
3.1 创建消息生产者
public class HelloWorldProducer3 {
public static void main(String[] args) {
HelloWorldProducer3 producer = new HelloWorldProducer3();
producer.sendHelloWorld(“Hello bjsxt”);
}

public void sendHelloWorld(String msg){
    //定义链接工厂
    ActiveMQConnectionFactory connectionFactory = null;
    //定义链接对象
    Connection connection = null;
    //定义会话
    Session session = null;
    //目的地
    Destination destination = null;
    //定义消息的发送者
    MessageProducer producer = null;
    //定义消息
    Message message = null;
    try{
        /**
         * userName:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * password:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * brokerURL:访问ActiveMQ服务的路径地址。路径结构为:协议名://主机地址:端口号
         */
        connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.40.138:61616");

        //创建连接对象
        connection = connectionFactory.createConnection();

        //启动连接
        connection.start();

        /**
         * transacted:是否使用事务 可选值为:true|false
         *            true:使用事务 当设置次变量值。Session.SESSION_TRANSACTED
         *            false:不适用事务,设置次变量 则acknowledgeMode参数必须设置
         * acknowledgeMode:
         * Session.AUTO_ACKNOWLEDGE:自动消息确认机制
         * Session.CLIENT_ACKNOWLEDGE:客户端确认机制
         * Session.DUPS_OK_ACKNOWLEDGE:有副本的客户端确认消息机制
         */
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地,目的地名称即队列的名称。消息的消费者需要通过此名称访问对应的队列
        destination = session.createQueue("helloworld");

        //创建消息的生产者
        producer = session.createProducer(destination);

        //创建消息对象
        message = session.createTextMessage(msg);

        //发送消息
        producer.send(message);

    }catch(Exception e){
        e.printStackTrace();
    }finally{

        //回收消息发送者资源
        if(producer != null){
            try {
                producer.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(session != null){
            try {
                session.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

}

3.2 消息消费者
public class HelloWorldConsumer3 {
public static void main(String[] args) {
HelloWorldConsumer3 consumer = new HelloWorldConsumer3();
consumer.readHelloWorld();
}
public void readHelloWorld(){
ActiveMQConnectionFactory
factory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
Message message = null;
try{
factory = new ActiveMQConnectionFactory(“admin”,“admin”,“tcp://192.168.40.138:61616”);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(“helloworld”);
consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
String text = null;
try {
text = ((TextMessage) message).getText();
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println(text);
}
});
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
finally {
try{
consumer.close();
}catch (Exception e){
e.printStackTrace();
}
try{
session.close();
}catch (Exception e){
e.printStackTrace();
}
try{
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}

七、 ActiveMQ的消息确认机制
AUTO_ACKNOWLEDGE :
自动确认,这就意味着消息的确认时机将有consumer择机确认.
"择机确认"似乎充满了不确定性,这也意味着,开发者必须明确知道"择机确认"的具体时机,否则将有可能导致消息的丢失,或者消息的重复接收.
CLIENT_ACKNOWLEDGE :
客户端手动确认,这就意味着AcitveMQ将不会“自作主张”的为你ACK任何消息,开发者需要自己择机确认。

4 Topic模型
4.1 Publish/Subscribe处理模式(Topic)
消息生产者(发布)将消息发布到topic中,同时有多个消息消费者(订阅)消费该消息。
和点对点方式不同,发布到topic的消息会被所有订阅者消费。
当生产者发布消息,不管是否有消费者。都不会保存消息
一定要先有消息的消费者,后有消息的生产者。

4.2 创建生产者
public class HelloWorldProducerTopic {
public static void main(String[] args) {
HelloWorldProducerTopic producer = new HelloWorldProducerTopic();
producer.sendHelloWorld(“Hello bjsxt”);
}

public void sendHelloWorld(String msg){
    //定义链接工厂
    ActiveMQConnectionFactory connectionFactory = null;
    //定义链接对象
    Connection connection = null;
    //定义会话
    Session session = null;
    //目的地
    Destination destination = null;
    //定义消息的发送者
    MessageProducer producer = null;
    //定义消息
    Message message = null;
    try{
        /**
         * userName:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * password:访问ActiveMQ服务的用户名。用户密码。默认的为admin。用户名可以通过jetty-ream.properties文件进行修改
         * brokerURL:访问ActiveMQ服务的路径地址。路径结构为:协议名://主机地址:端口号
         */
        connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.40.138:61616");

        //创建连接对象
        connection = connectionFactory.createConnection();

        //启动连接
        connection.start();

        /**
         * transacted:是否使用事务 可选值为:true|false
         *            true:使用事务 当设置次变量值。Session.SESSION_TRANSACTED
         *            false:不适用事务,设置次变量 则acknowledgeMode参数必须设置
         * acknowledgeMode:
         * Session.AUTO_ACKNOWLEDGE:自动消息确认机制
         * Session.CLIENT_ACKNOWLEDGE:客户端确认机制
         * Session.DUPS_OK_ACKNOWLEDGE:有副本的客户端确认消息机制
         */
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //创建目的地,目的地名称即队列的名称。消息的消费者需要通过此名称访问对应的队列
        destination = session.createTopic("my-topic");

        //创建消息的生产者
        producer = session.createProducer(destination);

        //创建消息对象
        message = session.createTextMessage(msg);

        //发送消息
        producer.send(message);

    }catch(Exception e){
        e.printStackTrace();
    }finally{

        //回收消息发送者资源
        if(producer != null){
            try {
                producer.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(session != null){
            try {
                session.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

}

4.3 创建消费者
public class HelloWorldConsumerTopic implements Runnable {
public static void main(String[] args) {
new Thread(new HelloWorldConsumerTopic()).start();
new Thread(new HelloWorldConsumerTopic()).start();
}
public void readHelloWorld(){
ConnectionFactory factory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
Message message = null;
try{
factory = new ActiveMQConnectionFactory(“admin”,“admin”,“tcp://192.168.40.138:61616”);
connection = factory.createConnection();
connection.start();
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
destination = session.createTopic(“my-topic”);
consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
String text = null;
try {
text = ((TextMessage) message).getText();
} catch (JMSException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+"\t"+text);
}
});
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
finally {
try{
consumer.close();
}catch (Exception e){
e.printStackTrace();
}
try{
session.close();
}catch (Exception e){
e.printStackTrace();
}
try{
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}

@Override
public void run() {
    this.readHelloWorld();
}

}

八、 Spring整合ActiveMQ
1 创建spring-activemq-producer
1.1 修改POM文件

org.springframework
spring-context-support
5.1.11.RELEASE

org.springframework spring-jms 5.1.11.RELEASE javax.jms javax.jms-api 2.0.1 org.apache.activemq activemq-all 5.15.10

1.2 整合ActiveMQ

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








<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory"

class=“org.springframework.jms.connection.SingleConnectionFactory”>


<!-- 配置Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
</bean>

<!--配置点对点-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <constructor-arg name="name" value="spring-queue"/>
</bean>
<!--配置发布订阅 -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg name="name" value="topic" />
</bean>

1.3 测试
@Test
public void sendMessage(){
ApplicationContext ac = new ClassPathXmlApplicationContext(“classpath:spring/applicationContext-producer.xml”);
//从Spring容器中获取JmsTemplate
JmsTemplate jmsTemplate = (JmsTemplate) ac.getBean(“jmsTemplate”);
//从Spring容器中获取Destination
Destination destination = (Destination) ac.getBean(“queueDestination”);
jmsTemplate.send(destination,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage(“Hello ActiveMQ”);
System.out.println(message);
return message;
}
});
}

2 创建spring-activemq-consumer
是一个jar工程
2.1 修改POM文件

org.springframework
spring-context-support
5.1.11.RELEASE

org.springframework spring-jms 5.1.11.RELEASE javax.jms javax.jms-api 2.0.1 org.apache.activemq activemq-all 5.15.10

2.2 整合ActiveMQ

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








<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory"
      class="org.springframework.jms.connection.SingleConnectionFactory">
    <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
    <property name="targetConnectionFactory" ref="targetConnectionFactory" />
</bean>

<!-- 配置Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
</bean>

<!--配置点对点-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
    <constructor-arg name="name" value="spring-queue"/>
</bean>
<!--配置发布订阅 -->
<bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg name="name" value="topic" />
</bean>
<!-- 接收消息 -->
<!-- 配置监听器 -->
<bean id="myMessageListener" class="com.bjsxt.MyMessageListener"/>
<!-- 消息监听容器 -->
<!-- 注册监听器 -->
<!-- 配置监听容器
        SimpleMessageListenerContainer最简单的消息监听器容器,只能处理固定数量的JMS会话,且不支持事务。
        DefaultMessageListenerContainer是一个用于异步消息监听器容器 ,且支持事务
        destination 目的地类型. 使用队列作为目的地.
        connectionFactory 连接工厂, spring-jms使用的连接工厂,必须是spring自主创建的
        不能ActiveMQConnectionFactory.
 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="queueDestination" />
    <property name="messageListener" ref="myMessageListener" />
   <!--
    AUTO_ACKNOWLEDGE = 1 :自动确认
    CLIENT_ACKNOWLEDGE = 2:客户端手动确认 
    DUPS_OK_ACKNOWLEDGE = 3: 自动批量确认
    SESSION_TRANSACTED = 0:事务提交并确认
    INDIVIDUAL_ACKNOWLEDGE = 4:单条消息确认(自定义的ACK模式)
    -->
    <property name="sessionAcknowledgeMode" value="1"/>
</bean>

2.3 测试
@Test
public void readMessage()throws Exception{
ApplicationContext ac = new ClassPathXmlApplicationContext(“classpath:spring/applicationContext-consumer.xml”);
System.in.read();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值