一、ptp
1. 测试案例
1). 工厂构造方法
创建连接工厂, 连接ActiveMQ服务的连接工厂.
创建工厂, 构造方法有三个参数, 分别是用户名, 密码, 连接地址
无参构造,有默认的链接地址。
单参数构造,无验证模式的。 没有用户的认证。
三参数构造,有认证+指定地址。 默认端口是61616
具体查看:ActiveMQConnectionFactory类
2). 客户端消息确认方式
static final int AUTO_ACKNOWLEDGE = 1;自动确认,不适合商业开发
static final int CLIENT_ACKNOWLEDGE = 2;客户端手动确认
static final int DUPS_OK_ACKNOWLEDGE = 3;会出现重复消费
2.使用监听器的方式, 实现消息的处理
消费端。生产者参考上面测试案例。
/**
* 处理消息.
*/
public void consumMessage(){
ConnectionFactory factory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageConsumer consumer = null;
try{
factory = new ActiveMQConnectionFactory("admin", "admin",
"tcp://192.168.1.8:61616");
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = session.createQueue("test-listener");
consumer = session.createConsumer(destination);
// 最大空闲时间
// consumer.receive(timeout);
// 注册监听器。 注册成功后,队列中的消息变化会自动触发监听器代码。 接收消息并处理。
consumer.setMessageListener(new MessageListener(){
/*
* 监听器注册后和消费者线程生命周期一致
*/
@Override
public void onMessage(Message message) {
try{
message.acknowledge();
ObjectMessage om = (ObjectMessage) message;
Object data = om.getObject();
System.out.println(data);
}catch(JMSException e){
e.printStackTrace();
}
}
});
// 阻塞,模拟实际场景。
System.in.read();
}catch(Exception e){
e.printStackTrace();
}finally{
各种关闭,回收消费者,关闭会话,关闭链接。伪代码....
consumer/session/connection.close();
}
public static void main(String[] args) {
ConsumerListener listener = new ConsumerListener();
listener.consumMessage();
}
二、topic
和ptp(createQueue)代码区别,创建目的地的时候,改成了创建topic
// 创建主题目的地
destination = session.createTopic(“test-topic”);
案例参考
三、消息发送
接口MessageProducer
void send(Message message) throws JMSException;
// 消息,是否持久化,优先级,消息有效期
void send(Message message, int deliveryMode, int priority, long timeToLive)
throws JMSException;
void send(Destination destination, Message message) throws JMSException;
void send(
Destination destination,
Message message,
int deliveryMode,
int priority,
long timeToLive)
throws JMSException;
消息过期后,默认会将失效消息保存到“死信队列(ActiveMQ.DLQ)”。
不持久化的消息,在超时后直接丢弃,不会保存到死信队列中。
死信队列名称可配置,死信队列中的消息不能恢复。
死信队列是在activemq.xml中配置的。
四、 集群
其它无差别。配置了多个节点,底层自动转移了。
factory = new ActiveMQConnectionFactory(“admin”, “admin”,
“failover:(tcp://192.168.159.130:61616,tcp://192.168.159.130:61617,tcp://192.168.159.130:61618)?Randomize=false”);