记录下activemq例子
一.activemq安全配置
1.配置监控台的用户名和密码:
操作文件为:conf文件夹下的jetty-realm.properties,原本是admin: admin, admin将第二个admin修改为新密码;
2.配置消息发送和获取时的用户名和密码:
操作文件为:conf文件夹下的activemq.xml,在broker节点新增以下配置
<plugins>
<simpleAuthenticationPlugin>
<users>
<authenticationUser username="admin" password="123456" groups="users,admins"/>
</users>
</simpleAuthenticationPlugin>
</plugins>
name就是要定义的用户名,password就是要定义的密码
二:code
public class Sender {
public static void main(String[] args) throws Exception {
// 第一步:建立ConnectionFactory工厂对象
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "123456", "tcp://localhost:61616");
// 第二步:创建connection连接, 连接默认是关闭的,需要开启
Connection connection = connectionFactory.createConnection();
connection.start();
// 第三步:获取session会话,用于接收消息,参数配置1为是否启用事务,参数配置2是签收模式,一般设置自动签收
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
// 第四步:通过session创建destination对象,指的是生产者生产消息的存放地与消费者消费消息的来源对象。在PFP(point to point
// 点对点)的模式中,destination指的就是队列。在pub/sub(订阅)模式中,destination指的就是topic
Destination destination = session.createQueue("first");
// 第五步:通过会话创建消息的发送者
// 创建发送对象,此时不指定消息发送到哪里,可以在发送时再指定,这样配置更加灵活。
MessageProducer messageProducer = session.createProducer(null);
for (int i = 0; i < 100; i++) {
TextMessage msg = session.createTextMessage("我是消息" + i);
messageProducer.send(destination, msg);
TimeUnit.SECONDS.sleep(1);
}
if (connection != null) {
connection.close();
}
}
}
public class Receiver {
public static void main(String[] args) throws Exception {
// 第一步:建立ConnectionFactory工厂对象
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://localhost:61616");
// 第二步:创建connection连接, 连接默认是关闭的,需要开启
Connection connection = connectionFactory.createConnection();
connection.start();
// 第三步:获取session会话,用于接收消息,参数配置1为是否启用事务,参数配置2是签收模式,一般设置自动签收
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
// 第四步:通过session创建destination对象,指的是生产者生产消息的存放地与消费者消费消息的来源对象。在PFP(point to point
// 点对点)的模式中,destination指的就是队列。在pub/sub(订阅)模式中,destination指的就是topic
Destination destination = session.createQueue("first");
// 第五步:通过会话创建消息的发送和接收对象
MessageConsumer consumer=session.createConsumer(destination);
// 设置监听器
consumer.setMessageListener(new Listener());
}
static class Listener implements MessageListener {
@Override
public void onMessage(Message message) {
// 根据业务处理消息
if (message instanceof TextMessage) {
TextMessage textMsg = (TextMessage) message;
try {
String str = textMsg.getText();
System.out.println(str);
} catch (JMSException e) {
e.printStackTrace();
}
} else if (message instanceof MapMessage) {
} // ...
}
}
}