Hello ActiveMQ
importorg.apache.activemq.ActiveMQConnectionFactory;
importjavax.jms.*;
/**
*消息的生产者(发送者)
*
*@authorleizhimin2009-8-1211:41:20
*/
publicclassJmsSender{
publicstaticvoidmain(String[]args)throwsJMSException{
//ConnectionFactory:连接工厂,JMS用它创建连接
ConnectionFactoryconnectionFactory=newActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
"tcp://192.168.14.117:61616");
//JMS客户端到JMSProvider的连接
Connectionconnection=connectionFactory.createConnection();
connection.start();
//Session:一个发送或接收消息的线程
Sessionsession=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
//Destination:消息的目的地;消息发送给谁.
//获取session注意参数值my-queue是Query的名字
Destinationdestination=session.createQueue("my-queue");
//MessageProducer:消息生产者
MessageProducerproducer=session.createProducer(destination);
//设置不持久化
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
//发送一条消息
sendMsg(session,producer);
session.commit();
connection.close();
}
/**
*在指定的会话上,通过指定的消息生产者发出一条消息
*
*@paramsession消息会话
*@paramproducer消息生产者
*/
publicstaticvoidsendMsg(Sessionsession,MessageProducerproducer)throwsJMSException{
//创建一条文本消息
TextMessagemessage=session.createTextMessage("HelloActiveMQ!");
//通过消息生产者发出消息
producer.send(message);
System.out.println("");
}
}importorg.apache.activemq.ActiveMQConnectionFactory;
importjavax.jms.*;
/**
*消息的消费者(接受者)
*
*@authorleizhimin2009-8-1211:41:33
*/
publicclassJmsReceiver{
publicstaticvoidmain(String[]args)throwsJMSException{
//ConnectionFactory:连接工厂,JMS用它创建连接
ConnectionFactoryconnectionFactory=newActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
"tcp://192.168.14.117:61616");
//JMS客户端到JMSProvider的连接
Connectionconnection=connectionFactory.createConnection();
connection.start();
//Session:一个发送或接收消息的线程
Sessionsession=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
//Destination:消息的目的地;消息发送给谁.
//获取session注意参数值xingbo.xu-queue是一个服务器的queue,须在在ActiveMq的console配置
Destinationdestination=session.createQueue("my-queue");
//消费者,消息接收者
MessageConsumerconsumer=session.createConsumer(destination);
while(true){
TextMessagemessage=(TextMessage)consumer.receive(1000);
if(null!=message)
System.out.println("收到消息:"+message.getText());
else
break;
}
session.close();
connection.close();
}
}Processfinishedwithexitcode0
收到消息HelloActiveMQ!
收到消息HelloActiveMQ!
Processfinishedwithexitcode0
<transportConnectors>
<transportConnectorname="openwire"uri="tcp://localhost:61616"discoveryUri="multicast://default"/>
<transportConnectorname="ssl"uri="ssl://localhost:61617"/>
<transportConnectorname="stomp"uri="stomp://localhost:61613"/>
<transportConnectorname="xmpp"uri="xmpp://localhost:61222"/>
</transportConnectors>