activeMQ学习笔记

开发环境:

Eclipse:Indigo Service Release 2
Tomcat:6.0
ActiveMQ:5.6

新建web工程RMI_TEST

导入activemq.jar等包

新建servlet:JMSListener
内容如下:

public class JMSListener extends HttpServlet implements ServletContextListener,
Serializable, MessageListener {

public void contextInitialized(ServletContextEvent arg0) {
try {
InitialContext initctx = new InitialContext();
Context envContext = (Context) initctx.lookup("java:comp/env");
ConnectionFactory connectionFactory = (ConnectionFactory) envContext
.lookup("jms/FailoverConnectionFactory");
Connection connection = connectionFactory.createConnection();
connection.setClientID("jerry");
Session jmsSession = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
TopicSubscriber consumer = jmsSession.createDurableSubscriber(
(Topic) envContext.lookup("jms/topic/MyTopic"), "MySub");
consumer.setMessageListener((MessageListener) this);
connection.start();
} catch (Exception e) {
e.printStackTrace();
}
}

private static String checkText(Message m, String s) {
try {
return m.getStringProperty(s);
} catch (JMSException e) {
e.printStackTrace();
return null;
}
}

public void onMessage(Message message) {
if (checkText(message, "RefreshArticleId") != null) {
String articleId = checkText(message, "RefreshArticleId");
System.out.println("接收刷新文章消息,开始刷新文章ID=" + articleId);
}
if (checkText(message, "RefreshThreadId") != null) {
String articleId = checkText(message, "RefreshThreadId");
System.out.println("接收刷新线程消息,开始刷新线程ID=" + articleId);
}
}

public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub

}

}

新建servlet:TestServlet
内容如下:

public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

try {
InitialContext initCtx = new InitialContext();
Context envContext = (Context) initCtx.lookup("java:comp/env");
ConnectionFactory connectionFactory = (ConnectionFactory) envContext
.lookup("jms/NormalConnectionFactory");
Connection connection = connectionFactory.createConnection();
Session jmsSession = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = jmsSession
.createProducer((Destination) envContext
.lookup("jms/topic/MyTopic"));
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
Message testMessage = jmsSession.createMessage();
testMessage.setStringProperty("RefreshArticleId", "2046");
producer.send(testMessage);
testMessage.clearProperties();
testMessage.setStringProperty("RefreshThreadId", "331");
producer.send(testMessage);
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}

String arg1 = request.getParameter("arg1");
response.setContentType("text/xml;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
Date responseTimestamp = new Date();
response.getWriter().write(
"<response><r><d id='a'><e id='a'>" + arg1 + responseTimestamp
+ "</e></d></r>" + "</response>");
}

}

web.xml新增如下配置:

<servlet>
    <servlet-name>JMSListener</servlet-name>
    <servlet-class>org.mq.test.JMSListener</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <listener>
    <listener-class>org.mq.test.JMSListener</listener-class>
  </listener>
  <servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.sides.server.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>

新建tomcat服务器,添加新工程:RMI_TEST

tomcat配置文件context.xml中context标签内新增如下配置:
<Resource name="jms/FailoverConnectionFactory" auth="Container"
type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS Connection Factory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
brokerURL="failover:(tcp://localhost:61616)?initialReconnectDelay=100&amp;maxReconnectAttempts=5"
brokerName="localhost" useEmbeddedBroker="false" />


<Resource name="jms/NormalConnectionFactory" auth="Container"
type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS Connection Factory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory" brokerURL="tcp://localhost:61616"
brokerName="localhost" useEmbeddedBroker="false" />

<Resource name="jms/topic/MyTopic" auth="Container"
type="org.apache.activemq.command.ActiveMQTopic" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
physicalName="MY.TEST.FOO" />

<Resource name="jms/queue/MyQueue" auth="Container"
type="org.apache.activemq.command.ActiveMQQueue" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
physicalName="MY.TEST.FOO.QUEUE" />

开启ActiveMQ、打开tomcat。
打开浏览器:http://localhost:8080/RMI_TEST/TestServlet,后台即可输出。


非web程序访问:


新建java类:HelloWorldProducer:


public class HelloWorldProducer implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
try {
// 创建连接工厂//vm://localhost
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"linfenliang","123456","tcp://0.0.0.0:61616");

// 创建连接
Connection connection = connectionFactory.createConnection();
connection.start();
/**
JMS 消息只有在被确认之后,才认为已经被成功地消费了。消息的成功消费通
常包含三个阶段:客户接收消息、客户处理消息和消息被确认。
在事务性会话中,当一个事务被提交的时候,确认自动发生。在非事务性会
话中,消息何时被确认取决于创建会话时的应答模式(acknowledgement mode)。
session的应答模式
Session.AUTO_ACKNOWLEDGE;
当客户成功的从receive方法返回的时候,或者从MessageListener.onMessage
方法成功返回的时候,会话自动确认客户收到的消息。
Session.CLIENT_ACKNOWLEDGE;
客户通过消息的acknowledge
方法确认消息。需要注意的是,在这种模式中,确认是在会话层上进行:确认一个被消费的消息将自动确认所有已被会话消费的消息。例如,如果一个消息消费者消费了10
个消息,然后确认第5 个消息,那么所有10 个消息都被确 认。
Session.DUPS_OK_ACKNOWLEDGE;
该选择只是会话迟钝的确认消息的提交。如果JMS provider 失败,那么可能会导致一些重复的消息。如果是重复的消息,那么JMS
provider 必须把消息头的JMSRedelivered 字段设置为 true。
**/
// 创建Session
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

/**
在点对点消息传递域中,目的地被成为队列(queue);在发布/订阅消息传递
域中,目的地被成为主题(topic)。
*/
// 创建消息的目的地
// Destination destination = session.createQueue("TEST.FOO");
Destination destination = session.createTopic("DEST");
// 从消息对象会话中创建消息的生产者用于把消息发送到目的地(queue或topic)
MessageProducer producer = session.createProducer(destination);
/**
消息的提交模式分两种
PERSISTENT。指示JMS provider 持久保存消息,以保证消息不会因为JMS provider 的失败而丢失。
· NON_PERSISTENT。不要求JMS provider 持久保存消息。
*/
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// producer.setDeliveryMode(DeliveryMode.PERSISTENT);
// 生成的消息内容
String text = "Hello world! From: "
+ Thread.currentThread().getName() + " : "
+ this.hashCode();
/**
JMS 消息由以下三部分组成:
消息头。每个消息头字段都有相应的getter 和setter 方法。
消息属性。如果需要除消息头字段以外的值,那么可以使用消息属性。
消息体。JMS 定义的消息类型有TextMessage、MapMessage、BytesMessage、StreamMessage 和 ObjectMessage。
*/
TextMessage message = session.createTextMessage(text);

System.out.println("Sent message: " + message.hashCode() + " : "
+ Thread.currentThread().getName());
//生产者开始生产消息
producer.send(message);
// 关闭
session.close();
connection.close();
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}

}

}

新建java类HelloWorldConsumer:

public class HelloWorldConsumer implements Runnable, ExceptionListener {
static int NUM = 0;


@Override
public synchronized void onException(JMSException arg0) {
// TODO Auto-generated method stub
System.out.println("JMS Exception occured.  Shutting down client.");
}

@Override
public void run() {
// TODO Auto-generated method stub
try {

// Create a ConnectionFactory
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"linfenliang","123456","tcp://0.0.0.0:61616");

// Create a Connection
Connection connection = connectionFactory.createConnection();
connection.start();

connection.setExceptionListener(this);

// Create a Session
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

// Create the destination (Topic or Queue)
// Destination destination = session.createQueue("TEST.FOO");
Destination destination = session.createTopic("DEST");

// Create a MessageConsumer from the Session to the Topic or Queue
MessageConsumer consumer = session.createConsumer(destination);

// Wait for a message
Message message = consumer.receive();
System.out.println(NUM++);
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println("Received: " + text);
} else {
System.out.println("_Received_null: " + message);
}

consumer.close();
session.close();
connection.close();
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}

}

新建java文件:App

public class App {
/**
* Hello world!
*/
public static void main(String[] args) throws Exception {
thread(new HelloWorldProducer(), false);
for (int i = 0; i < 5; i++) {
thread(new HelloWorldConsumer(), false);
}
}

public static void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}

}

开启activeMQ,运行App。

说明:此处新建连接工厂connectionFactory的时候,增加了用户名密码。

在activeMQ中,配置如下:

conf文件夹中:

修改 jmx.access

新增:
lin readonly
linfenliang readwrite

此处配置用户名及权限



修改jmx.password

新增:
lin 123
linfenliang 123456

此处配置用户名密码


Bin文件夹
修改activemq.bat

REM set SUNJMX=-Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false

改为:

REM set SUNJMX=-Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=%ACTIVEMQ_BASE%/conf/jmx.password -Dcom.sun.management.jmxremote.access.file=%ACTIVEMQ_BASE%/conf/jmx.access

重启activeMQ。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值