JMS( Java Message Service)即 java消息服务 用于分布式系统得消息通信,JMS是J2EE技术中的一个部分,Sun公司定义了JMS的标准接口,即javax.jms.*。
JMS服务使得分布式系统的信息通信松散连接的,发送信息的客户端只需要负责发送信息,接收信息的客户端接收信息,两个客户端之间没有必要是同时可用的,甚至发送客户端都没有必要知道客户端的信息,只要负责发送到接收的服务端就可以,JMS可以说是低耦合的。
同时JMS API 做到了以下2点
异步的,服务端可以发送信息到一个客户端,客户端不需要为了收到信息而请求信息。
可靠的,JMS API保证了服务端所有发送的信息最少发送一次和只发送一次
下面介绍一些JMS API 的基本知识
JMS API 基本组成
JMS provider服务者,是一个消息系统通过实现JMS API 接口,用于管理和控制信息。
JMS client 客户端 用于发送和接收信息,通常是用在java程序中用java编写的
Messages 用于在客户端信息通信的对象
Administered Objects 由JMS provider为了client创建的对象,通常是connectionFactory和destination
Messages 通信方式
JMS通信方式分为点对点通信,和发布/订阅方式
点对点方式(point-to-point)
点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存贮消息,Sneder 发送消息,receive接收消息,
具体的信息就是 Sender Client发送Message 到Queue ,而 receiver Cliernt 从Queue中接收消息和发送消息已接受到Quere,确认消息接收。
在使用点对点方式时需要注意,
一条消息只有一个接收端,消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行
发布/订阅 方式(publish/subscriber Messaging)
发布/订阅方式用于多接收客户端的方式
作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。
作为subscriber ,在接收消息时有两种方法,destination的receive方法,和实现message listener 接口的onMessage 方法。
基础知识这里说的很少,具体的可以参照java.sun.com.的JMS API 指南
下面说下JMS API Programming Client的基本组成,
作为一个JMS client 都需要以下的组成
Administered Objects:ConnectionFactory,Destination
Connection;
Session
Message Producers/Message Cosumers
Messages
至于如何编程提供一个Topic的Active mq的例子供大家参考
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"
; you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Arrays;
import java.util.Date;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.util.IndentPrinter;
/**
* A simple tool for publishing messages
*
*
*/
public class ProducerTool {
private Destination destination;
private int messageCount = 10;
private long sleepTime = 0L;
private boolean verbose = true;
private int messageSize = 255;
private long timeToLive;
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private String subject = "TOOL.DEFAULT";
private boolean topic = false;
private boolean transacted = false;
private boolean persistent = false;
public static void main(String[] args) {
ProducerTool producerTool = new ProducerTool();
String[] unknonwn = CommnadLineSupport.setOptions(producerTool, args);
if( unknonwn.length > 0 ) {
System.out.println("Unknown options: "+Arrays.toString(unknonwn));
System.exit(-1);
}
producerTool.run();
}
public void run() {
Connection connection=null;
try {
System.out.println("Connecting to URL: " + url);
System.out.println("Publishing a Message with size " + messageSize+ " to " + (topic ? "topic" : "queue"
+ ": " + subject);
System.out.println("Using " + (persistent ? "persistent" : "non-persistent"
+ " messages"
;
System.out.println("Sleeping between publish " + sleepTime + " ms"
;
if (timeToLive != 0) {
System.out.println("Messages time to live " + timeToLive + " ms"
;
}
// Create the connection.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connection = connectionFactory.createConnection();
connection.start();
// Create the session
Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
if (topic) {
destination = session.createTopic(subject);
} else {
destination = session.createQueue(subject);
}
// Create the producer.
MessageProducer producer = session.createProducer(destination);
if (persistent) {
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
} else {
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
if (timeToLive != 0)
producer.setTimeToLive(timeToLive);
// Start sending messages
sendLoop(session, producer);
System.out.println("Done."
;
// Use the ActiveMQConnection interface to dump the connection stats.
ActiveMQConnection c = (ActiveMQConnection) connection;
c.getConnectionStats().dump(new IndentPrinter());
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
}
}
}
protected void sendLoop(Session session, MessageProducer producer)
throws Exception {
for (int i = 0; i < messageCount || messageCount == 0; i++) {
TextMessage message = session
.createTextMessage(createMessageText(i));
if (verbose) {
String msg = message.getText();
if (msg.length() > 50) {
msg = msg.substring(0, 50) + "...";
}
System.out.println("Sending message: " + msg);
}
producer.send(message);
if (transacted) {
session.commit();
}
Thread.sleep(sleepTime);
}
}
private String createMessageText(int index) {
StringBuffer buffer = new StringBuffer(messageSize);
buffer.append("Message: " + index + " sent at: " + new Date());
if (buffer.length() > messageSize) {
return buffer.substring(0, messageSize);
}
for (int i = buffer.length(); i < messageSize; i++) {
buffer.append(' ');
}
return buffer.toString();
}
public void setPersistent(boolean durable) {
this.persistent = durable;
}
public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}
public void setMessageSize(int messageSize) {
this.messageSize = messageSize;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public void setSleepTime(long sleepTime) {
this.sleepTime = sleepTime;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
public void setTopic(boolean topic) {
this.topic = topic;
}
public void setQueue(boolean queue) {
this.topic = !queue;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
}