RabbitMQ实例详解

来源:互联网 发布:pack php 编辑:程序博客网 时间:2024/05/16 17:39
  • http://blog.csdn.net/chwshuang/article/category/6066031
  • http://stephansun.iteye.com/blog/1452853

  • 使用Git从GitHub上将samples代码拷贝到本机,然后导入到IDE中
Shell代码  收藏代码
  1. git clone git://github.com/stephansun/samples.git  
samples包含7个模块,分别为
  1. samples-jms-plain:使用JMS原生API;
  2. samples-jms-spring:使用Spring对JMS原生API封装后的spring-jms;
  3. samples-jms-spring-remoting:使用spring-jms实现JMS的请求/响应模式,需要用到spring提供的远程调用框架;
  4. samples-spring-remoting:介绍spring的远程调用框架;
  5. samples-amqp-plain:使用RabbitMQ提供的AMQP Java客户端;
  6. samples-amqp-spring:使用spring对AMQP Java客户端封装后的spring-amqp-rabbit;
  7. samples-amqp-spring-remoting:使用spring-amqp-rabbit实现AMQP的请求/响应模式,需要用到spring提供的远程调用框架;
下面逐一讲解

samples-amqp-plain

pom.xml
Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>com.rabbitmq</groupId>  
  4.         <artifactId>amqp-client</artifactId>  
  5.         <version>2.5.0</version>  
  6.         <exclusions>  
  7.             <exclusion>  
  8.                 <groupId>commons-cli</groupId>  
  9.                 <artifactId>commons-cli</artifactId>  
  10.             </exclusion>  
  11.         </exclusions>  
  12.     </dependency>  
  13.   </dependencies>  
 amqp-client-2.5.0.jar以及它依赖的commons-io-1.2.jar加载进来了,常用的类有:
Java代码  收藏代码
  1. com.rabbitmq.client.BasicProperties  
  2. com.rabbitmq.client.Channel  
  3. com.rabbitmq.client.Connection  
  4. com.rabbitmq.client.ConnectionFactory  
  5. com.rabbitmq.client.Consumer  
  6. com.rabbitmq.client.MessageProperties  
  7. com.rabbitmq.client.QueueingConsumer  

helloworld

Send.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.helloworld;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class Send {  
  10.   
  11.     private final static String QUEUE_NAME = "hello";  
  12.       
  13.     public static void main(String[] args) throws IOException {  
  14.         // AMQP的连接其实是对Socket做的封装, 注意以下AMQP协议的版本号,不同版本的协议用法可能不同。  
  15.         ConnectionFactory factory = new ConnectionFactory();  
  16.         factory.setHost("localhost");  
  17.         Connection connection = factory.newConnection();  
  18.         // 下一步我们创建一个channel, 通过这个channel就可以完成API中的大部分工作了。  
  19.         Channel channel = connection.createChannel();  
  20.           
  21.         // 为了发送消息, 我们必须声明一个队列,来表示我们的消息最终要发往的目的地。  
  22.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  23.         String message = "Hello World!";  
  24.         // 然后我们将一个消息发往这个队列。  
  25.         channel.basicPublish("", QUEUE_NAME, null, message.getBytes());  
  26.         System.out.println("[" + message + "]");  
  27.           
  28.         // 最后,我们关闭channel和连接,释放资源。  
  29.         channel.close();  
  30.         connection.close();  
  31.     }  
  32. }  
 RabbitMQ默认有一个exchange,叫default exchange,它用一个空字符串表示,它是direct exchange类型,任何发往这个exchange的消息都会被路由到routing key的名字对应的队列上,如果没有对应的队列,则消息会被丢弃。这就是为什么代码中channel执行basicPulish方法时,第二个参数本应该为routing key,却被写上了QUEUE_NAME。
Recv.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.helloworld;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.ConsumerCancelledException;  
  9. import com.rabbitmq.client.QueueingConsumer;  
  10. import com.rabbitmq.client.ShutdownSignalException;  
  11.   
  12. public class Recv {  
  13.   
  14.     private final static String QUEUE_NAME = "hello";  
  15.       
  16.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  17.         ConnectionFactory factory = new ConnectionFactory();  
  18.         factory.setHost("localhost");  
  19.         Connection connection = factory.newConnection();  
  20.         Channel channel = connection.createChannel();  
  21.           
  22.         // 注意我们也在这里声明了一个queue,因为我们有可能在发送者启动前先启动接收者。  
  23.         // 我们要确保当从这个queue消费消息时,这个queue是存在的。  
  24.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  25.         System.out.println("CRTL+C");  
  26.           
  27.         // 这个另外的QueueingConsumer类用来缓存服务端推送给我们的消息。  
  28.         // 下面我们准备告诉服务端给我们传递存放在queue里的消息,因为消息是由服务端推送过来的。  
  29.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  30.         channel.basicConsume(QUEUE_NAME, true, consumer);  
  31.           
  32.         while (true) {  
  33.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  34.             String message = new String(delivery.getBody());  
  35.             System.out.println("[" + message + "]");  
  36.         }  
  37.     }  
  38. }  
channel.queueDeclare:第一个参数:队列名字,第二个参数:队列是否可持久化即重启后该队列是否依然存在,第三个参数:该队列是否时独占的即连接上来时它占用整个网络连接,第四个参数:是否自动销毁即当这个队列不再被使用的时候即没有消费者对接上来时自动删除,第五个参数:其他参数如TTL(队列存活时间)等。
channel.basicConsume:第一个参数:队列名字,第二个参数:是否自动应答,如果为真,消息一旦被消费者收到,服务端就知道该消息已经投递,从而从队列中将消息剔除,否则,需要在消费者端手工调用channel.basicAck()方法通知服务端,如果没有调用,消息将会进入unacknowledged状态,并且当消费者连接断开后变成ready状态重新进入队列,第三个参数,具体消费者类。

work queues

Worker.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.workqueues;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.ConsumerCancelledException;  
  9. import com.rabbitmq.client.QueueingConsumer;  
  10. import com.rabbitmq.client.ShutdownSignalException;  
  11.   
  12. public class Worker {  
  13.   
  14.     private final static String QUEUE_NAME = "task_queue";  
  15.       
  16.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  17.         ConnectionFactory factory = new ConnectionFactory();  
  18.         factory.setHost("localhost");  
  19.         Connection connection = factory.newConnection();  
  20.         Channel channel = connection.createChannel();  
  21.           
  22.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  23.         System.out.println("CRTL+C");  
  24.           
  25.         // 这条语句告诉RabbitMQ在同一时间不要给一个worker一个以上的消息。  
  26.         // 或者换一句话说, 不要将一个新的消息分发给worker知道它处理完了并且返回了前一个消息的通知标志(acknowledged)  
  27.         // 替代的,消息将会分发给下一个不忙的worker。  
  28.         channel.basicQos(1);  
  29.           
  30.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  31.         // 自动通知标志  
  32.         boolean autoAck = false;  
  33.         channel.basicConsume(QUEUE_NAME, autoAck, consumer);  
  34.           
  35.         while (true) {  
  36.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  37.             String message = new String(delivery.getBody());  
  38.             System.out.println("r[" + message + "]");  
  39.             doWord(message);  
  40.             System.out.println("r[done]");  
  41.             // 发出通知标志  
  42.             channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
  43.         }  
  44.     }  
  45.   
  46.     private static void doWord(String task) throws InterruptedException {  
  47.         for (char ch : task.toCharArray()) {  
  48.             if (ch == '.') {  
  49.                 Thread.sleep(1000);  
  50.             }  
  51.         }  
  52.     }  
  53. }  
在本代码中,
channel执行basicConsume方法时autoAck为false,这就意味着接受者在收到消息后需要主动通知RabbitMQ才能将该消息从队列中删除,否则该在接收者跟MQ连接没断的情况下,消息将会变为untracked状态,一旦接收者断开连接,消息重新变为ready状态。
通知MQ需要调用channel.basicAck(int, boolean),如果不调用,消息永远不会从队列中消失。
该方法第一个参数为一个标志,一般是delivery.getEnvelope().getDeliveryTag(),其实就是一个递增的数字,它表示这个这个队列中第几个消息。
以下解释错误!
第二个参数为true表示通知所有untracked的消息,false标志只通知第一个参数对应的那个消息。不管是true还是false,只要执行了channel.basicAck方法,消息都会从队列中删除。
第二个参数
Java代码  收藏代码
  1. Parameters:  
  2. deliveryTag the tag from the received com.rabbitmq.client.AMQP.Basic.GetOk or com.rabbitmq.client.AMQP.Basic.Deliver  
  3. multiple true to acknowledge all messages up to and including the supplied delivery tag; false to acknowledge just the supplied delivery tag.  
 我之前错误的将and作为的断句点,认为true通知所有的untracked消息,包含tag指定的那个,其实应该将 up to and including 作为一个整体理解,通知所有拥有相同tag的untracked消息(暂时还没有在代码中模拟出这种场景)。尼玛英语不好害死人啊。参考这个版本的API 

 NewTask.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.workqueues;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.MessageProperties;  
  9.   
  10. public class NewTask {  
  11.       
  12.     // 使用Work Queues (也称为Task Queues)最主要的想法是分流那些耗时,耗资源的任务,不至于使队列拥堵。   
  13.   
  14.     private static String getMessage(String[] strings) {  
  15.         if (strings.length < 1) {  
  16.             return "Hello World!";  
  17.         }  
  18.         return joinStrings(strings, " ");  
  19.     }  
  20.   
  21.     private static String joinStrings(String[] strings, String delimiter) {  
  22.         int length = strings.length;  
  23.         if (length == 0) {  
  24.             return "";  
  25.         }  
  26.         StringBuilder words = new StringBuilder(strings[0]);  
  27.         for (int i = 1; i < length; i++) {  
  28.             words.append(delimiter).append(strings[i]);  
  29.         }  
  30.         return words.toString();  
  31.     }  
  32.       
  33.     private final static String QUEUE_NAME = "task_queue";  
  34.       
  35.     public static void main(String[] args) throws IOException {  
  36.         String[] strs = new String[] { "First message." };  
  37.           
  38.         ConnectionFactory factory = new ConnectionFactory();  
  39.         factory.setHost("localhost");  
  40.         Connection connection = factory.newConnection();  
  41.         Channel channel = connection.createChannel();  
  42.           
  43.         // 跟helloworld的不同点  
  44.         boolean durable = true;  
  45.         // 下面这个声明队列的队列名字改了,所以生产者和消费者两边的程序都要改成统一的队列名字。  
  46.         channel.queueDeclare(QUEUE_NAME, durable, falsefalsenull);  
  47.         // 有了durable为true,我们可以保证名叫task_queue的队列即使在RabbitMQ重启的情况下也不会消失。  
  48.         String message = getMessage(strs);  
  49.         // 现在我们需要将消息标记成可持久化的。  
  50.         // 如果你需要更强大的保证消息传递,你可以将发布消息的代码打包到一个事务里。   
  51.         channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());  
  52.         System.out.println("s[" + message + "]");  
  53.           
  54.         channel.close();  
  55.         connection.close();  
  56.     }  
  57. }  

 publish subscribe

EmitLog.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.publishsubscribe;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class EmitLog {  
  10.       
  11.     // 在前面,我们使用queue,都给定了一个指定的名字。能够对一个queue命名对于我们来说是很严肃的  
  12.     // 下面我们需要将worker指定到同一个queue。  
  13.       
  14.     // echange的类型有: direct, topic, headers and fanout.  
  15.   
  16.     private static final String EXCHANGE_NAME = "logs";  
  17.       
  18.     public static void main(String[] args) throws IOException {  
  19.           
  20.         ConnectionFactory factory = new ConnectionFactory();  
  21.         factory.setHost("localhost");  
  22.         Connection connection = factory.newConnection();  
  23.         Channel channel = connection.createChannel();  
  24.           
  25.         // fanout exchange 将它收的所有消息广播给它知道的所有队列。  
  26.         channel.exchangeDeclare(EXCHANGE_NAME, "fanout");  
  27.           
  28.         String message = getMessage(new String[] { "test" });  
  29.           
  30.         // 如果routingkey存在的话,消息通过一个routingkey指定的名字路由至队列  
  31.         channel.basicPublish(EXCHANGE_NAME, ""null, message.getBytes());  
  32.         System.out.println("sent [" + message + "]");  
  33.           
  34.         channel.close();  
  35.         connection.close();  
  36.     }  
  37.       
  38.     private static String getMessage(String[] strings) {  
  39.         if (strings.length < 1) {  
  40.             return "Hello World!";  
  41.         }  
  42.         return joinStrings(strings, " ");  
  43.     }  
  44.   
  45.     private static String joinStrings(String[] strings, String delimiter) {  
  46.         int length = strings.length;  
  47.         if (length == 0) {  
  48.             return "";  
  49.         }  
  50.         StringBuilder words = new StringBuilder(strings[0]);  
  51.         for (int i = 1; i < length; i++) {  
  52.             words.append(delimiter).append(strings[i]);  
  53.         }  
  54.         return words.toString();  
  55.     }  
  56. }  
 ReceiveLogs.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.publishsubscribe;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.ConsumerCancelledException;  
  9. import com.rabbitmq.client.QueueingConsumer;  
  10. import com.rabbitmq.client.ShutdownSignalException;  
  11.   
  12. public class ReceiveLogs {  
  13.       
  14.     // 就像你看到的, 创建了连接后,我们声明了一个exchange,这一步是必须的,因为将消息发送到一个并不存在的exchange上是不允许的。  
  15.     // 如果还没有queue绑定到exchange上,消息将会丢失。  
  16.     // 但那对我们来说是ok的。  
  17.     // 如果没有消费者在监听,我们可以安全地丢弃掉消息。  
  18.       
  19.     // RabbitMQ中有关消息模型地核心观点是,生产者永远不会直接将消息发往队列。  
  20.     // 事实上,相当多的生产者甚至根本不知道一个消息是否已经传递给了一个队列。  
  21.     // 相反,生产者只能将消息发送给一个exchange。  
  22.     // exchange是一个很简单的东西。  
  23.     // 一边它接收来自生产者的消息,另一边它将这些消息推送到队列。  
  24.     // exchagne必须明确地知道拿它收到的消息来做什么。把消息附在一个特定的队列上?把消息附在很多队列上?或者把消息丢弃掉。  
  25.     // 这些规则在exchange类型里都有定义。  
  26.   
  27.     private static final String EXCHANGE_NAME = "logs";  
  28.       
  29.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  30.           
  31.         ConnectionFactory factory = new ConnectionFactory();  
  32.         factory.setHost("localhost");  
  33.         Connection connection = factory.newConnection();  
  34.         Channel channel = connection.createChannel();  
  35.           
  36.         // 创建fanout类型的exchange, 我们叫它logs:  
  37.         // 这种类型的exchange将它收到的所有消息广播给它知道的所有队列。  
  38.         channel.exchangeDeclare(EXCHANGE_NAME, "fanout");  
  39.         // 临时队列(temporary queue)  
  40.         // 首先,无论什么时候连接Rabbit时,我们需要一个fresh的,空的队列  
  41.         // First, whenever we connect to Rabbit we need a fresh, empty queue.  
  42.         // 为了做到这一点,我们可以创建一个随机命名的队列,或者更好的,就让服务端给我们选择一个随机的队列名字。  
  43.         // 其次,一旦我们关闭消费者的连接,这个临时队列应该自动销毁。  
  44.         String queueName = channel.queueDeclare().getQueue();  
  45.         channel.queueBind(queueName, EXCHANGE_NAME, "");  
  46.           
  47.         System.out.println("CTRL+C");  
  48.           
  49.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  50.         channel.basicConsume(queueName, true, consumer);  
  51.           
  52.         while (true) {  
  53.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  54.             String message = new String(delivery.getBody());  
  55.               
  56.             System.out.println("r[" + message + "]");  
  57.         }  
  58.     }     
  59. }  
 发布订阅,本代码演示的是fanout exchange,这种类型的exchange将它收到的所有消息直接发送给所有跟它绑定的队列,这里说了直接,是因为rouring key对于fanout exchange来说没有任何意义!不管一个队列以怎样的routing key和fanout exhange绑定,只要他们绑定了,消息就会送到队列。代码中发送端将消息发到logs名字的fanout exchange,routing key为空字符串,你可以将它改成任何其他值或者null试试看。另外,接收端代码使用channel声明了一个临时队列,并将这个队列通过空字符串的routing key绑定到fanout exchange。这个临时队列的名字的随机取的,如:amq.gen-U0srCoW8TsaXjNh73pnVAw==,临时队列在后面的请求响应模式中有用到。

routing

EmitLogDirect.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.routing;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class EmitLogDirect {  
  10.   
  11.     private static final String EXCHANGE_NAME = "direct_logs";  
  12.       
  13.     public static void main(String[] args) throws IOException {  
  14.           
  15.         ConnectionFactory factory = new ConnectionFactory();  
  16.         factory.setHost("localhost");  
  17.         Connection connection = factory.newConnection();  
  18.         Channel channel = connection.createChannel();  
  19.           
  20.         channel.exchangeDeclare(EXCHANGE_NAME, "direct");  
  21.           
  22.         // diff  
  23.         String serverity = getServerity(new String[] { "test" });  
  24.         String message = getMessage(new String[] { "test" });  
  25.           
  26.         channel.basicPublish(EXCHANGE_NAME, serverity, null, message.getBytes());  
  27.         System.out.println("s[" + serverity + "]:[" + message + "]");  
  28.           
  29.         channel.close();  
  30.         connection.close();  
  31.           
  32.     }  
  33.   
  34.     private static String getServerity(String[] strings) {  
  35.         return "info";  
  36.     }  
  37.       
  38.     private static String getMessage(String[] strings) {  
  39.         if (strings.length < 1) {  
  40.             return "Hello World!";  
  41.         }  
  42.         return joinStrings(strings, " ");  
  43.     }  
  44.   
  45.     private static String joinStrings(String[] strings, String delimiter) {  
  46.         int length = strings.length;  
  47.         if (length == 0) {  
  48.             return "";  
  49.         }  
  50.         StringBuilder words = new StringBuilder(strings[0]);  
  51.         for (int i = 1; i < length; i++) {  
  52.             words.append(delimiter).append(strings[i]);  
  53.         }  
  54.         return words.toString();  
  55.     }  
  56. }  
 ReceiveLogsDirect.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.routing;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.ConsumerCancelledException;  
  9. import com.rabbitmq.client.QueueingConsumer;  
  10. import com.rabbitmq.client.ShutdownSignalException;  
  11.   
  12. public class ReceiveLogsDirect {  
  13.   
  14.     private static final String EXCHANGE_NAME = "direct_logs";  
  15.       
  16.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  17.           
  18.         ConnectionFactory factory = new ConnectionFactory();  
  19.         factory.setHost("localhost");  
  20.         Connection connection = factory.newConnection();  
  21.         Channel channel = connection.createChannel();  
  22.           
  23.         channel.exchangeDeclare(EXCHANGE_NAME, "direct");  
  24.         String queueName = channel.queueDeclare().getQueue();  
  25.           
  26.         String[] strs = new String[] { "info""waring""error" };  
  27.         for (String str : strs) {  
  28.             channel.queueBind(queueName, EXCHANGE_NAME, str);  
  29.         }  
  30.           
  31.         System.out.println("CTRL+C");  
  32.           
  33.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  34.         channel.basicConsume(queueName, true, consumer);  
  35.           
  36.         while (true) {  
  37.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  38.             String message = new String(delivery.getBody());  
  39.             String routingKey = delivery.getEnvelope().getRoutingKey();  
  40.               
  41.             System.out.println("r:[" + routingKey + "]:[" + message + "]");  
  42.         }  
  43.     }  
  44. }  
 本代码演示了另外一种exchange,direct exchange,该exchange根据routing key将消息发往使用该routing key和exchange绑定的一个或者多个队列里,如果没找到,则消息丢弃。本代码中可以启动3个接收端,分别使用info,warning,error作为routing key,代表3种级别的日志。只要将不同级别的日志发往不同接收端只需将日志级别当作routing key。

topics

EmitLogTopic.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.topics;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class EmitLogTopic {  
  10.   
  11.     private static final String EXCHANGE_NAME = "topic_logs";  
  12.       
  13.     public static void main(String[] args) throws IOException {  
  14.           
  15.         ConnectionFactory factory = new ConnectionFactory();  
  16.         factory.setHost("localhost");  
  17.         Connection connection = factory.newConnection();  
  18.         Channel channel = connection.createChannel();  
  19.           
  20.         channel.exchangeDeclare(EXCHANGE_NAME, "topic");  
  21.           
  22.         // diff  
  23.         String routingKey = getServerity(new String[] { "test" });  
  24.         String message = getMessage(new String[] { "test" });  
  25.           
  26.         channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());  
  27.         System.out.println("s[" + routingKey + "]:[" + message + "]");  
  28.           
  29.         channel.close();  
  30.         connection.close();  
  31.           
  32.     }  
  33.   
  34.     private static String getServerity(String[] strings) {  
  35.         return "kern.critical";  
  36.     }  
  37.       
  38.     private static String getMessage(String[] strings) {  
  39.         if (strings.length < 1) {  
  40.             return "Hello World!";  
  41.         }  
  42.         return joinStrings(strings, " ");  
  43.     }  
  44.   
  45.     private static String joinStrings(String[] strings, String delimiter) {  
  46.         int length = strings.length;  
  47.         if (length == 0) {  
  48.             return "";  
  49.         }  
  50.         StringBuilder words = new StringBuilder(strings[0]);  
  51.         for (int i = 1; i < length; i++) {  
  52.             words.append(delimiter).append(strings[i]);  
  53.         }  
  54.         return words.toString();  
  55.     }  
  56. }  
 ReceiveLogsTopic.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.topics;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.ConsumerCancelledException;  
  9. import com.rabbitmq.client.QueueingConsumer;  
  10. import com.rabbitmq.client.ShutdownSignalException;  
  11.   
  12. public class ReceiveLogsTopic {  
  13.       
  14.     // FIXME  
  15.     // Some teasers:  
  16.     // Will "*" binding catch a message sent with an empty routing key?  
  17.     // Will "#.*" catch a message with a string ".." as a key? Will it catch a message with a single word key?  
  18.     // How different is "a.*.#" from "a.#"?  
  19.   
  20.     private static final String EXCHANGE_NAME = "topic_logs";  
  21.       
  22.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  23.           
  24.         ConnectionFactory factory = new ConnectionFactory();  
  25.         factory.setHost("localhost");  
  26.         Connection connection = factory.newConnection();  
  27.         Channel channel = connection.createChannel();  
  28.           
  29.         channel.exchangeDeclare(EXCHANGE_NAME, "topic");  
  30.         String queueName = channel.queueDeclare().getQueue();  
  31.           
  32.         String[] strs = new String[] { "kern.critical""A critical kernel error" };  
  33.         for (String str : strs) {  
  34.             channel.queueBind(queueName, EXCHANGE_NAME, str);  
  35.         }  
  36.           
  37.         System.out.println("CTRL+C");  
  38.           
  39.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  40.         channel.basicConsume(queueName, true, consumer);  
  41.           
  42.         while (true) {  
  43.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  44.             String message = new String(delivery.getBody());  
  45.             String routingKey = delivery.getEnvelope().getRoutingKey();  
  46.               
  47.             System.out.println("r:[" + routingKey + "]:[" + message + "]");  
  48.         }  
  49.     }  
  50. }  
 本代码演示了最后一种类型的exchange,topic exchange,topic exchange和direct exchange最大的不同就是它绑定的routing key是一种模式,而不是简单的一个字符串。为什么要有模式(Patten)这个概念?模式可以理解为对事物描述的一种抽象。以代码种的日志系统为例,使用direct exchange只能区别info,error,debug等等不同级别的日志,但是实际上不光有不同级别的日志,还有不同来源的日志,如操作系统内核的日志,定时脚本等, 使用模式就可以用<level>.<source>表示,更强大的是,模式允许使用通配符,*代表一个单词,#代表一个多个单词。

RPC

RPCClient.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.rpc;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.UUID;  
  5.   
  6. import com.rabbitmq.client.AMQP.BasicProperties;  
  7. import com.rabbitmq.client.Channel;  
  8. import com.rabbitmq.client.Connection;  
  9. import com.rabbitmq.client.ConnectionFactory;  
  10. import com.rabbitmq.client.ConsumerCancelledException;  
  11. import com.rabbitmq.client.QueueingConsumer;  
  12. import com.rabbitmq.client.ShutdownSignalException;  
  13.   
  14. public class RPCClient {  
  15.       
  16.     // FIXME  
  17.     // AMQP协议预定义了14种伴随着消息的属性。大多数属性很少使用到。除了以下这些异常情况:  
  18.     // deliveryMode:  
  19.     // contentType:  
  20.     // replyTo:  
  21.     // correlationId:   
  22.       
  23.     // FIXME  
  24.     // 为什么我们忽略掉callback队列里的消息,而不是抛出错误?  
  25.     // 这取决于服务端的竞争条件的可能性。  
  26.     // 虽然不太可能,但这种情况是存在的,即  
  27.     // RPC服务在刚刚将答案发给我们,然而没等我们将通知标志后返回时就死了  
  28.     // 如果发生了这种情况, 重启的RPC服务将会重新再次处理该请求。  
  29.     // 这就是为什么在客户端我们必须优雅地处理重复性的响应,及RPC在理想情况下应该时幂等的。(不太理解这句话的意思)  
  30.   
  31.     private Connection connection;  
  32.     private Channel channel;  
  33.     private String requestQueueName = "rpc_queue";  
  34.     private String replyQueueName;  
  35.     private QueueingConsumer consumer;  
  36.       
  37.     public RPCClient() throws IOException {  
  38.         ConnectionFactory factory = new ConnectionFactory();  
  39.         factory.setHost("localhost");  
  40.         connection = factory.newConnection();  
  41.         channel = connection.createChannel();  
  42.           
  43.         // temporary queue.  
  44.         replyQueueName = channel.queueDeclare().getQueue();  
  45.         consumer = new QueueingConsumer(channel);  
  46.         channel.basicConsume(replyQueueName, true, consumer);  
  47.     }  
  48.       
  49.     public String call(String message) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  50.         String response = null;  
  51.         String corrId = UUID.randomUUID().toString();  
  52.           
  53.         // in order to receive a response we need to send a 'callback' queue address with the request.  
  54.         // We can use the default queue(which is exclusive in the Java client)  
  55.         BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();  
  56.           
  57.         channel.basicPublish("", requestQueueName, props, message.getBytes());  
  58.           
  59.         while (true) {  
  60.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  61.             if (delivery.getProperties().getCorrelationId().equals(corrId)) {  
  62.                 response = new String(delivery.getBody(), "UTF-8");  
  63.                 break;  
  64.             }  
  65.         }  
  66.           
  67.         return response;  
  68.     }  
  69.       
  70.     public void close() throws IOException {  
  71.         connection.close();  
  72.     }  
  73.       
  74.     public static void main(String[] args) {  
  75.         RPCClient fibonacciRpc = null;  
  76.         String response = null;  
  77.         try {  
  78.             fibonacciRpc = new RPCClient();  
  79.               
  80.             System.out.println("fib(30)");  
  81.             response = fibonacciRpc.call("30");  
  82.             System.out.println("got[" + response + "]");  
  83.         } catch (Exception e) {  
  84.             e.printStackTrace();  
  85.         } finally {  
  86.             if (fibonacciRpc != null) {  
  87.                 try {  
  88.                     fibonacciRpc.clone();  
  89.                 } catch (Exception ignore) {  
  90.                     // ignore  
  91.                 }  
  92.             }  
  93.         }  
  94.     }  
  95. }  
 RPCServer.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.plain.rpc;  
  2.   
  3. import com.rabbitmq.client.AMQP.BasicProperties;  
  4. import com.rabbitmq.client.Channel;  
  5. import com.rabbitmq.client.Connection;  
  6. import com.rabbitmq.client.ConnectionFactory;  
  7. import com.rabbitmq.client.QueueingConsumer;  
  8.   
  9. public class RPCServer {  
  10.   
  11.     // 我们的代码仍然相当简单,没有试图解决更复杂(或者更重要)的问题,像:  
  12.     // 客户端在没有服务端运行的情况下如何处理?  
  13.     // 一个RPC的客户端应该有一些超时类型吗?  
  14.     // 如果服务端出现异常,是否应该将异常返回给客户端?  
  15.     // 在进行业务处理前阻止不合法的消息进入(比如检查绑定,类型)  
  16.     // Protecting against invalid incoming messages (eg checking bounds, type) before processing.  
  17.   
  18.     private static final String RPC_QUEUE_NAME = "rpc_queue";  
  19.       
  20.     // FIXME Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible.  
  21.     private static int fib(int n) {  
  22.         if (n == 0) {  
  23.             return 0;  
  24.         }  
  25.         if (n == 1) {  
  26.             return 1;  
  27.         }  
  28.         return fib(n - 1) + fib(n - 2);  
  29.     }  
  30.       
  31.     public static void main(String[] args) {  
  32.         Connection connection = null;  
  33.         Channel channel = null;  
  34.         try {  
  35.             ConnectionFactory factory = new ConnectionFactory();  
  36.             factory.setHost("localhost");  
  37.               
  38.             connection = factory.newConnection();  
  39.             channel = connection.createChannel();  
  40.               
  41.             channel.queueDeclare(RPC_QUEUE_NAME, falsefalsefalsenull);  
  42.               
  43.             // We might want to run more than one server process.   
  44.             // In order to spread the load equally over multiple servers we need to set the prefetchCount setting in channel.basicQos.  
  45.             channel.basicQos(1);  
  46.               
  47.             QueueingConsumer consumer = new QueueingConsumer(channel);  
  48.             channel.basicConsume(RPC_QUEUE_NAME, false, consumer);  
  49.               
  50.             System.out.println("[x] Awaiting RPC requests");  
  51.               
  52.             while (true) {  
  53.                 String response = null;  
  54.                   
  55.                 QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  56.                   
  57.                 BasicProperties props = delivery.getProperties();  
  58.                 BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();  
  59.                   
  60.                 try {  
  61.                     String message = new String(delivery.getBody(), "UTF-8");  
  62.                     int n = Integer.parseInt(message);  
  63.                       
  64.                     System.out.println(" [.] fib(" + message + ")");  
  65.                     response = "" + fib(n);  
  66.                 } catch (Exception e) {  
  67.                     System.out.println(" [.] " + e.toString());  
  68.                     response = "";  
  69.                 } finally {  
  70.                     channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));  
  71.                       
  72.                     channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
  73.                 }  
  74.                   
  75.             }  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         } finally {  
  79.             if (connection != null) {  
  80.                 try {  
  81.                     connection.close();  
  82.                 } catch (Exception ignore) {  
  83.                     // ignore  
  84.                 }  
  85.             }  
  86.         }  
  87.     }  
  88. }  
 本代码实现了一个简单的RPC,英文全称Remote Procedure Call,中文一般翻译远程方法调用。RPC需要使用一个唯一标志代表请求,Java中使用java.util.UUID实现,发送端在发送消息前通过channel生成一个临时队列,并监听该队列,BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();这句代码生成的就是发送消息的基本属性,可以看到corrId就是UUID,replyQueueName就是临时队列名,这样当接收端收到消息后就知道返回的消息应该发回哪个队列了。

samples-amqp-spring

pom.xml
Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.springframework.amqp</groupId>  
  4.         <artifactId>spring-amqp-rabbit</artifactId>  
  5.         <version>1.0.0.RC1</version>  
  6.     </dependency>  
  7.   </dependencies>  
常用的类有:org.springframework.amqp.AmqpAdmin
Java代码  收藏代码
  1. org.springframework.amqp.AmqpTemplate  
  2. org.springframework.amqp.Binding  
  3. org.springframework.amqp.DirectExchange  
  4. org.springframework.amqp.FanoutExchange  
  5. org.springframework.amqp.TopicExchange  
  6. org.springframework.amqp.Message  
  7. org.springframework.amqp.MessageListener  
  8. org.springframework.amqp.MessageProperties  

 helloworld

Send.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.helloworld;  
  2.   
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  4. import org.springframework.amqp.support.converter.MessageConverter;  
  5. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class Send {  
  9.   
  10.     private final static String QUEUE_NAME = "hello";  
  11.       
  12.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  13.       
  14.     public static void main(String[] args) {  
  15.         ClassPathXmlApplicationContext applicationContext =  
  16.                 new ClassPathXmlApplicationContext(  
  17.                         "stephansun/github/samples/amqp/spring/helloworld/spring-rabbitmq.xml");  
  18.           
  19.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  20.           
  21.         String message = "Hello World!";  
  22.           
  23.         rabbitTempalte.send("", QUEUE_NAME, messageConverter.toMessage(message, null));  
  24.     }  
  25.       
  26. }  
Recv.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.helloworld;  
  2.   
  3. import org.springframework.amqp.core.Message;  
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  5. import org.springframework.amqp.support.converter.MessageConverter;  
  6. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8.   
  9. public class Recv {  
  10.   
  11.     private final static String QUEUE_NAME = "hello";  
  12.       
  13.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  14.       
  15.     public static void main(String[] args) {  
  16.         ClassPathXmlApplicationContext applicationContext =  
  17.                 new ClassPathXmlApplicationContext(  
  18.                         "stephansun/github/samples/amqp/spring/helloworld/spring-rabbitmq.xml");  
  19.           
  20.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  21.           
  22.         Message message = rabbitTempalte.receive(QUEUE_NAME);  
  23.           
  24.         Object obj = messageConverter.fromMessage(message);  
  25.           
  26.         System.out.println("received:[" + obj + "]");  
  27.           
  28.     }  
  29. }   
  spring-rabbitmq.xml
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24.     <rabbit:queue name="hello"  
  25.         durable="false"  
  26.         exclusive="false"  
  27.         auto-delete="false"/>  
  28.           
  29. </beans>  
我们着重讲解以下xml配置文件,第一行就给我们创建了一个mq的连接工厂,第二行创建了一个RabbitTemplate,这是一个模板类,定义了amqp中绝大多数的发送,接收方法。第三行是一个管理器,该bean在创建的时候,会在Spring Context中扫描所有已经注册的queue,exchange,binding并将他们初始化好。第四行声明了一个队列,所见即所得,可以发现使用xml节省了好多代码量。

work queues

MyWorker.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.workqueues;  
  2.   
  3. import org.springframework.amqp.core.Message;  
  4. import org.springframework.amqp.core.MessageProperties;  
  5. import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;  
  6. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  7.   
  8. import com.rabbitmq.client.Channel;  
  9.   
  10. public class MyWorker implements ChannelAwareMessageListener {  
  11.   
  12.     private void doWord(String task) {  
  13.         for (char ch : task.toCharArray()) {  
  14.             if (ch == '.') {  
  15.                 try {  
  16.                     Thread.sleep(1000);  
  17.                 } catch (InterruptedException e) {  
  18.                     e.printStackTrace();  
  19.                 }  
  20.             }  
  21.         }  
  22.         throw new RuntimeException("test exception");  
  23.     }  
  24.   
  25.     @Override  
  26.     public void onMessage(Message message, Channel channel) throws Exception {  
  27. System.out.println("MyWorker");  
  28.         MessageProperties messageProperties = message.getMessageProperties();  
  29.         String messageContent = (String) new SimpleMessageConverter().fromMessage(message);  
  30.         System.out.println("r[" + message + "]");  
  31.           
  32.         // 写在前面会怎样?  
  33.         // channel.basicAck(messageProperties.getDeliveryTag(), true);  
  34.           
  35.           
  36.         doWord(messageContent);  
  37. System.out.println("deliveryTag是递增的");  
  38. System.out.println(messageProperties.getDeliveryTag());  
  39.   
  40.         // 写在后面会怎样?  
  41.         // channel.basicAck(messageProperties.getDeliveryTag(), false);  
  42.   
  43.         System.out.println("r[done]");  
  44.     }  
  45.   
  46. }  
 NewTask.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.workqueues;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.springframework.amqp.core.Message;  
  6. import org.springframework.amqp.core.MessageProperties;  
  7. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  8. import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter;  
  9. import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;  
  10. import org.springframework.amqp.support.converter.MessageConverter;  
  11. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  12. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  13.   
  14. public class NewTask {  
  15.       
  16.     private static String getMessage(String[] strings) {  
  17.         if (strings.length < 1) {  
  18.             return "Hello World!";  
  19.         }  
  20.         return joinStrings(strings, " ");  
  21.     }  
  22.   
  23.     private static String joinStrings(String[] strings, String delimiter) {  
  24.         int length = strings.length;  
  25.         if (length == 0) {  
  26.             return "";  
  27.         }  
  28.         StringBuilder words = new StringBuilder(strings[0]);  
  29.         for (int i = 1; i < length; i++) {  
  30.             words.append(delimiter).append(strings[i]);  
  31.         }  
  32.         return words.toString();  
  33.     }  
  34.       
  35.     private final static String QUEUE_NAME = "task_queue";  
  36.       
  37.     public static void main(String[] args) throws IOException {  
  38.         ClassPathXmlApplicationContext applicationContext =  
  39.                 new ClassPathXmlApplicationContext(  
  40.                         "stephansun/github/samples/amqp/spring/workqueues/spring-rabbitmq-sender.xml");  
  41.           
  42.         RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  43.           
  44.         String[] strs = new String[] { "First message." };  
  45.   
  46.         String messageStr = getMessage(strs);  
  47.           
  48.         MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter();  
  49.         MessageProperties messageProperties =   
  50.                 messagePropertiesConverter.toMessageProperties(  
  51.                         com.rabbitmq.client.MessageProperties.PERSISTENT_TEXT_PLAIN, nullnull);  
  52.           
  53.         MessageConverter messageConverter = new SimpleMessageConverter();  
  54.         Message message = messageConverter.toMessage(messageStr, messageProperties);  
  55.         rabbitTemplate.send("", QUEUE_NAME, message);  
  56.           
  57.         System.out.println("s[" + message + "]");  
  58.           
  59.     }  
  60. }  
 Worker.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.workqueues;  
  2.   
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5. public class Worker {  
  6.   
  7.     public static void main(String[] args) {  
  8.         ClassPathXmlApplicationContext applicationContext =  
  9.                 new ClassPathXmlApplicationContext(  
  10.                         "stephansun/github/samples/amqp/spring/workqueues/spring-rabbitmq-receiver.xml");  
  11.     }  
  12. }  
 spring-rabbitmq-receiver.xml
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template   
  21.         id="rabbitTemplate"   
  22.         connection-factory="connectionFactory"  
  23.         channel-transacted="true"/>  
  24.       
  25.     <rabbit:admin connection-factory="connectionFactory"/>  
  26.       
  27.     <rabbit:queue name="task_queue"  
  28.         durable="true"  
  29.         exclusive="false"  
  30.         auto-delete="false"/>  
  31.           
  32.     <bean id="myWorker"  
  33.         class="stephansun.github.samples.amqp.spring.workqueues.MyWorker"/>  
  34.           
  35.     <rabbit:listener-container   
  36.         connection-factory="connectionFactory"   
  37.         acknowledge="none"  
  38.         prefetch="1">  
  39.         <rabbit:listener ref="myWorker" queue-names="task_queue"/>  
  40.     </rabbit:listener-container>  
  41.       
  42.           
  43. </beans>  
 spring-rabbit-sender.xml
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24.     <rabbit:queue name="task_queue"  
  25.         durable="true"  
  26.         exclusive="false"  
  27.         auto-delete="false"/>  
  28.           
  29. </beans>  
 具体区别可以通过与前面RabbitMQ 原生API写的代码做对照看出来。

publish subscribe

EmitLog.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.publishsubscribe;  
  2.   
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  4. import org.springframework.amqp.support.converter.MessageConverter;  
  5. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class EmitLog {  
  9.       
  10.     private static final String EXCHANGE_NAME = "logs";  
  11.       
  12.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  13.       
  14.     public static void main(String[] args) {  
  15.         ClassPathXmlApplicationContext applicationContext =  
  16.                 new ClassPathXmlApplicationContext(  
  17.                         "stephansun/github/samples/amqp/spring/publishsubscribe/spring-rabbitmq.xml");  
  18.           
  19.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  20.           
  21.         String message = getMessage(new String[] { "test" });  
  22.         rabbitTempalte.send(EXCHANGE_NAME, "", messageConverter.toMessage(message, null));  
  23.         System.out.println("sent [" + message + "]");  
  24.     }  
  25.       
  26.     private static String getMessage(String[] strings) {  
  27.         if (strings.length < 1) {  
  28.             return "Hello World!";  
  29.         }  
  30.         return joinStrings(strings, " ");  
  31.     }  
  32.   
  33.     private static String joinStrings(String[] strings, String delimiter) {  
  34.         int length = strings.length;  
  35.         if (length == 0) {  
  36.             return "";  
  37.         }  
  38.         StringBuilder words = new StringBuilder(strings[0]);  
  39.         for (int i = 1; i < length; i++) {  
  40.             words.append(delimiter).append(strings[i]);  
  41.         }  
  42.         return words.toString();  
  43.     }  
  44. }  
 ReceiveLogs.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.publishsubscribe;  
  2.   
  3. import org.springframework.amqp.core.Binding;  
  4. import org.springframework.amqp.core.Binding.DestinationType;  
  5. import org.springframework.amqp.core.FanoutExchange;  
  6. import org.springframework.amqp.core.Message;  
  7. import org.springframework.amqp.rabbit.core.RabbitAdmin;  
  8. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  9. import org.springframework.amqp.support.converter.MessageConverter;  
  10. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  12.   
  13. public class ReceiveLogs {  
  14.       
  15.     private static final String EXCHANGE_NAME = "logs";  
  16.       
  17.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  18.       
  19.     public static void main(String[] args) {  
  20.         ClassPathXmlApplicationContext applicationContext =  
  21.                 new ClassPathXmlApplicationContext(  
  22.                         "stephansun/github/samples/amqp/spring/publishsubscribe/spring-rabbitmq.xml");  
  23.           
  24.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  25.   
  26.         RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);  
  27.   
  28.         FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME);  
  29.         rabbitAdmin.declareExchange(fanoutExchange);  
  30.         String queueName = rabbitAdmin.declareQueue().getName();  
  31.         Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, ""null);  
  32.         rabbitAdmin.declareBinding(binding);  
  33.           
  34.         System.out.println("CTRL+C");  
  35.           
  36.         // FIXME 为什么要在这里暂停10秒钟?  
  37.         try {  
  38.             Thread.sleep(10000);  
  39.         } catch (InterruptedException e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.           
  43.         Message message = rabbitTempalte.receive(queueName);  
  44.         Object obj = messageConverter.fromMessage(message);  
  45.           
  46.         System.out.println("received:[" + obj + "]");  
  47.           
  48.     }     
  49. }  
 spring-rabbitmq.xml
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24. </beans>  

 routing

EmitLogDirect.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.routing;  
  2.   
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  4. import org.springframework.amqp.support.converter.MessageConverter;  
  5. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class EmitLogDirect {  
  9.   
  10.     private static final String EXCHANGE_NAME = "direct_logs";  
  11.       
  12.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  13.       
  14.     public static void main(String[] args) {  
  15.           
  16.         ClassPathXmlApplicationContext applicationContext =  
  17.                 new ClassPathXmlApplicationContext(  
  18.                         "stephansun/github/samples/amqp/spring/routing/spring-rabbitmq.xml");  
  19.           
  20.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  21.           
  22.         // diff  
  23.         String serverity = getServerity(new String[] { "test" });  
  24.         String message = getMessage(new String[] { "test" });  
  25.           
  26.         rabbitTempalte.send(EXCHANGE_NAME, serverity, messageConverter.toMessage(message, null));  
  27.         System.out.println("s[" + serverity + "]:[" + message + "]");  
  28.     }  
  29.   
  30.     private static String getServerity(String[] strings) {  
  31.         return "info";  
  32.     }  
  33.       
  34.     private static String getMessage(String[] strings) {  
  35.         if (strings.length < 1) {  
  36.             return "Hello World!";  
  37.         }  
  38.         return joinStrings(strings, " ");  
  39.     }  
  40.   
  41.     private static String joinStrings(String[] strings, String delimiter) {  
  42.         int length = strings.length;  
  43.         if (length == 0) {  
  44.             return "";  
  45.         }  
  46.         StringBuilder words = new StringBuilder(strings[0]);  
  47.         for (int i = 1; i < length; i++) {  
  48.             words.append(delimiter).append(strings[i]);  
  49.         }  
  50.         return words.toString();  
  51.     }  
  52. }  
 ReceiveLogsDirect.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.routing;  
  2.   
  3. import org.springframework.amqp.core.Binding;  
  4. import org.springframework.amqp.core.Binding.DestinationType;  
  5. import org.springframework.amqp.core.DirectExchange;  
  6. import org.springframework.amqp.core.Message;  
  7. import org.springframework.amqp.rabbit.core.RabbitAdmin;  
  8. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  9. import org.springframework.amqp.support.converter.MessageConverter;  
  10. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  12.   
  13. public class ReceiveLogsDirect {  
  14.   
  15.     private static final String EXCHANGE_NAME = "direct_logs";  
  16.       
  17.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  18.       
  19.     public static void main(String[] args) {  
  20.         ClassPathXmlApplicationContext applicationContext =  
  21.                 new ClassPathXmlApplicationContext(  
  22.                         "stephansun/github/samples/amqp/spring/routing/spring-rabbitmq.xml");  
  23.           
  24.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  25.   
  26.         RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);  
  27.   
  28.         DirectExchange directExchange = new DirectExchange(EXCHANGE_NAME);  
  29.         rabbitAdmin.declareExchange(directExchange);  
  30.         String queueName = rabbitAdmin.declareQueue().getName();  
  31.         String[] strs = new String[] { "info""waring""error" };  
  32.         for (String str : strs) {  
  33.             Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, str, null);  
  34.             rabbitAdmin.declareBinding(binding);  
  35.         }  
  36.           
  37.         System.out.println("CTRL+C");  
  38.           
  39.         // FIXME 请你先思考一下,为什么要在这里暂停10秒钟?然后问我。  
  40.         try {  
  41.             Thread.sleep(10000);  
  42.         } catch (InterruptedException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.           
  46.         Message message = rabbitTempalte.receive(queueName);  
  47.         Object obj = messageConverter.fromMessage(message);  
  48.           
  49.         System.out.println("received:[" + obj + "]");  
  50.     }  
  51. }  
 spring-rabbitmq.xml
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24. </beans>  
实际上exchange,binding的声明完全可以放在xml中,只是为了展示封装的代码底层到底是如何运行的,才在程序中手工调用方法。

topics

EmitLogsTopic.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.topics;  
  2.   
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  4. import org.springframework.amqp.support.converter.MessageConverter;  
  5. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class EmitLogTopic {  
  9.   
  10.     private static final String EXCHANGE_NAME = "topic_logs";  
  11.       
  12.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  13.       
  14.     public static void main(String[] args) {  
  15.           
  16.         ClassPathXmlApplicationContext applicationContext =  
  17.                 new ClassPathXmlApplicationContext(  
  18.                         "stephansun/github/samples/amqp/spring/topics/spring-rabbitmq.xml");  
  19.           
  20.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  21.           
  22.         // diff  
  23.         String serverity = getServerity(new String[] { "test" });  
  24.         String message = getMessage(new String[] { "test" });  
  25.           
  26.         rabbitTempalte.send(EXCHANGE_NAME, serverity, messageConverter.toMessage(message, null));  
  27.         System.out.println("s[" + serverity + "]:[" + message + "]");  
  28.     }  
  29.   
  30.     private static String getServerity(String[] strings) {  
  31.         return "kern.critical";  
  32.     }  
  33.       
  34.     private static String getMessage(String[] strings) {  
  35.         if (strings.length < 1) {  
  36.             return "Hello World!";  
  37.         }  
  38.         return joinStrings(strings, " ");  
  39.     }  
  40.   
  41.     private static String joinStrings(String[] strings, String delimiter) {  
  42.         int length = strings.length;  
  43.         if (length == 0) {  
  44.             return "";  
  45.         }  
  46.         StringBuilder words = new StringBuilder(strings[0]);  
  47.         for (int i = 1; i < length; i++) {  
  48.             words.append(delimiter).append(strings[i]);  
  49.         }  
  50.         return words.toString();  
  51.     }  
  52.       
  53. }  
 ReceiveLogsTopic.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.topics;  
  2.   
  3. import org.springframework.amqp.core.Binding;  
  4. import org.springframework.amqp.core.Binding.DestinationType;  
  5. import org.springframework.amqp.core.Message;  
  6. import org.springframework.amqp.core.TopicExchange;  
  7. import org.springframework.amqp.rabbit.core.RabbitAdmin;  
  8. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  9. import org.springframework.amqp.support.converter.MessageConverter;  
  10. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  12.   
  13. public class ReceiveLogsTopic {  
  14.       
  15.   
  16.     private static final String EXCHANGE_NAME = "topic_logs";  
  17.       
  18.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  19.       
  20.     public static void main(String[] args) {  
  21.         ClassPathXmlApplicationContext applicationContext =  
  22.                 new ClassPathXmlApplicationContext(  
  23.                         "stephansun/github/samples/amqp/spring/topics/spring-rabbitmq.xml");  
  24.           
  25.         RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  26.   
  27.         RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);  
  28.   
  29.         TopicExchange directExchange = new TopicExchange(EXCHANGE_NAME);  
  30.         rabbitAdmin.declareExchange(directExchange);  
  31.         String queueName = rabbitAdmin.declareQueue().getName();  
  32.         String[] strs1 = new String[] { "#" };  
  33.         String[] strs2 = new String[] { "kern.*" };  
  34.         String[] strs3 = new String[] { "*.critical" };  
  35.         String[] strs4 = new String[] { "kern.*""*.critical" };  
  36.         String[] strs5 = new String[] { "kern.critical""A critical kernel error" };  
  37.         for (String str : strs5) {  
  38.             Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, str, null);  
  39.             rabbitAdmin.declareBinding(binding);  
  40.         }  
  41.           
  42.         System.out.println("CTRL+C");  
  43.           
  44.         // FIXME 为什么要在这里暂停10秒钟?  
  45.         try {  
  46.             Thread.sleep(30000);  
  47.         } catch (InterruptedException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.           
  51.         Message message = rabbitTempalte.receive(queueName);  
  52.         Object obj = messageConverter.fromMessage(message);  
  53.           
  54.         System.out.println("received:[" + obj + "]");  
  55.     }  
  56.       
  57. }  
 spring-rabbitmq.xml
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24. </beans>  

 rpc

RPCClient.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.rpc;  
  2.   
  3. import org.springframework.amqp.core.Message;  
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  5. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class RPCClient {  
  9.       
  10.     private static String requestQueueName = "rpc_queue";  
  11.       
  12.     public static void main(String[] args) {  
  13.         ClassPathXmlApplicationContext applicationContext =  
  14.                 new ClassPathXmlApplicationContext(  
  15.                         "stephansun/github/samples/amqp/spring/rpc/spring-rabbitmq-client.xml");  
  16.           
  17.         RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");  
  18.           
  19.         String message = "30";  
  20.         Message reply = rabbitTemplate.sendAndReceive("", requestQueueName, new SimpleMessageConverter().toMessage(message, null));  
  21.           
  22.         if (reply == null) {  
  23.             System.out.println("接收超时,返回null");  
  24.         } else {  
  25.             System.out.println("接收到消息:");  
  26.             System.out.println(reply);  
  27.         }  
  28.     }  
  29. }  
 RPCServer.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.rpc;  
  2.   
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5. public class RPCServer {  
  6.   
  7.     public static void main(String[] args) {  
  8.         ClassPathXmlApplicationContext applicationContext =  
  9.                 new ClassPathXmlApplicationContext(  
  10.                         "stephansun/github/samples/amqp/spring/rpc/spring-rabbitmq-server.xml");  
  11.     }  
  12. }  
 RPCServerListener.java
Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.rpc;  
  2.   
  3. import org.springframework.amqp.core.Message;  
  4. import org.springframework.amqp.core.MessageListener;  
  5. import org.springframework.amqp.rabbit.core.RabbitTemplate;  
  6. import org.springframework.amqp.support.converter.MessageConverter;  
  7. import org.springframework.amqp.support.converter.SimpleMessageConverter;  
  8.   
  9. public class RPCServerListener implements MessageListener {  
  10.   
  11.     private RabbitTemplate rabbitTemplate;  
  12.   
  13.     private static MessageConverter messageConverter = new SimpleMessageConverter();  
  14.       
  15.     public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {  
  16.         this.rabbitTemplate = rabbitTemplate;  
  17.     }  
  18.   
  19.     @Override  
  20.     public void onMessage(Message requestMessage) {  
  21.         Object obj = messageConverter.fromMessage(requestMessage);  
  22.         String str = (String) obj;  
  23.         int n = Integer.parseInt(str);  
  24.         System.out.println(" [.] fib(" + requestMessage + ")");  
  25.         String response = "" + fib(n);  
  26.         String replyTo = requestMessage.getMessageProperties().getReplyTo();  
  27.         rabbitTemplate.send(  
  28.                 "",   
  29.                 replyTo,   
  30.                 messageConverter.toMessage(response, null));  
  31.     }  
  32.   
  33.     private static int fib(int n) {  
  34.         if (n == 0) {  
  35.             return 0;  
  36.         }  
  37.         if (n == 1) {  
  38.             return 1;  
  39.         }  
  40.         return fib(n - 1) + fib(n - 2);  
  41.     }  
  42.   
  43. }  
 spring-rabbitmq-client.xml
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory" reply-timeout="1000"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.   
  24. </beans>  
spring-rabbitmq-server.xml
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.   
  24.     <rabbit:queue name="rpc_queue"  
  25.         durable="false"  
  26.         exclusive="false"  
  27.         auto-delete="false">  
  28.     </rabbit:queue>  
  29.       
  30.     <bean id="myListener"  
  31.         class="stephansun.github.samples.amqp.spring.rpc.RPCServerListener">  
  32.         <property name="rabbitTemplate" ref="rabbitTemplate"/>      
  33.     </bean>  
  34.       
  35.     <rabbit:listener-container connection-factory="connectionFactory" prefetch="1">  
  36.         <rabbit:listener queue-names="rpc_queue" ref="myListener"/>  
  37.     </rabbit:listener-container>  
  38.       
  39. </beans>  
  本代码演示了监听器的用法,RabbitTemplate提供的所有方法都是同步的,所有当使用RabbitTemplate的receive方法时,它马上连接到队列,查看是否由消息,有就收下来,并关闭连接,没有也不抛出异常,只返回一个null值。这就解释了为什么我上面代码中多次使用sleep10秒,因为如果先运行接收端,它不能不停循环地收消息,所以在发送端还没发消息时,它就已经结束了。而监听器(Listener)不一样,底层代码中会使用org.springframework.amqp.rabbit.listener.SimepleMessageListenerContainer中的内部类AsyncMessageProcessingConsumer实现,该类为一个线程类,在线程的run方法中执行了while的一段代码。RabbitTemplate提供了一个sendAndReceive()方法,它实现了一个简单的RPC模型。这里还有一个prefetch的含义,该含义同原生API中的Qos一样。

spring-amqp-spring-remoting

随后会讲到Spring远程调用框架,在此先把代码列出来

Main.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.remoting;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class Main {  
  9.   
  10.     public static void main(String[] args) {  
  11.         ClassPathXmlApplicationContext applicationContext =  
  12.                 new ClassPathXmlApplicationContext(new String[] {  
  13.                         "stephansun/github/samples/amqp/spring/remoting/amqp-remoting.xml",  
  14.                         "stephansun/github/samples/amqp/spring/remoting/amqp-remoting-sender.xml",  
  15.                         "stephansun/github/samples/amqp/spring/remoting/amqp-remoting-receiver.xml"  
  16.                 });  
  17.         MyService sender = (MyService) applicationContext.getBean("sender");  
  18.         sender.sayHello();  
  19.           
  20.         Map<String, Object> param = new HashMap<String, Object>();  
  21.         param.put("name""stephan");  
  22.         param.put("age"26);  
  23.         String str = sender.foo(param);  
  24.         System.out.println("str:" + str);  
  25.     }  
  26. }  

 

 MyService.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.remoting;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public interface MyService {  
  6.   
  7.     void sayHello();  
  8.       
  9.     String foo(Map<String, Object> param);  
  10.       
  11. }  

 

 MyServiceImpl.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.amqp.spring.remoting;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public class MyServiceImpl implements MyService {  
  6.   
  7.     @Override  
  8.     public void sayHello() {  
  9.         System.out.println("hello world!");  
  10.     }  
  11.   
  12.     @Override  
  13.     public String foo(Map<String, Object> param) {  
  14.         return param.toString();  
  15.     }  
  16.   
  17. }  

 

 amqp-remoting-receiver.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.     <bean id="myService"  
  15.         class="stephansun.github.samples.amqp.spring.remoting.MyServiceImpl"/>  
  16.       
  17.     <bean id="receiver"  
  18.         class="org.springframework.amqp.remoting.AmqpInvokerServiceExporter">  
  19.         <property name="serviceInterface" value="stephansun.github.samples.amqp.spring.remoting.MyService"/>  
  20.         <property name="service" ref="myService"/>  
  21.     </bean>  
  22.       
  23.     <rabbit:listener-container   
  24.         connection-factory="connectionFactory">  
  25.         <rabbit:listener ref="receiver" queue-names="si.test.queue"/>  
  26.     </rabbit:listener-container>  
  27.           
  28. </beans>  

 

 amqp-remoting-sender.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.     <bean id="sender"  
  15.         class="org.springframework.amqp.remoting.AmqpInvokerProxyFactoryBean">  
  16.         <property name="amqpTemplate" ref="amqpTemplate"/>  
  17.         <property name="serviceInterface" value="stephansun.github.samples.amqp.spring.remoting.MyService"/>  
  18.         <property name="exchange" value="si.test.exchange"/>  
  19.         <property name="routingKey" value="si.test.binding"/>  
  20.     </bean>  
  21.           
  22. </beans>  

 

 amqp-remoting.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:rabbit="http://www.springframework.org/schema/rabbit"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/context  
  8.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.         http://www.springframework.org/schema/rabbit   
  10.         http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd  
  11.         http://www.springframework.org/schema/beans   
  12.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  13.   
  14.       
  15.       
  16.     <!-- Infrastructure -->  
  17.       
  18.     <rabbit:connection-factory id="connectionFactory"/>  
  19.       
  20.     <rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>  
  21.       
  22.     <rabbit:admin connection-factory="connectionFactory"/>  
  23.       
  24.     <rabbit:queue name="si.test.queue"/>  
  25.       
  26.     <rabbit:direct-exchange name="si.test.exchange">  
  27.         <rabbit:bindings>  
  28.             <rabbit:binding queue="si.test.queue" key="si.test.binding"/>  
  29.         </rabbit:bindings>  
  30.     </rabbit:direct-exchange>  
  31.           
  32. </beans>  

 

 关键的几个类有:

 

Java代码  收藏代码
  1. org.springframework.amqp.remoting.AmqpInvokerClientIntecrptor  
  2. org.springframework.amqp.remoting.AmqpInvokerProxyFactoryBean  
  3. org.springframework.amqp.remoting.AmqpInvokerServiceExporter  

 

 其中AmqpInvokerProxyFactoryBean继承与AmqpInvokerClientInterceptor

AmqpInvovkerServiceExporter除了继承了Spring远程调用框架的RemoteInvocationBasedExporter,还额外实现了ChannelAwareMessageListener接口,这个接口的handle方法处理消息,且实现该接口的类都可以被SimpleMessageListenerContainer管理起来。

samples-spring-remoting

下面我们写一段简单的代码初步领略一下Spring远程调用框架

pom.xml

 

Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.springframework</groupId>  
  4.         <artifactId>spring-context</artifactId>  
  5.         <version>3.1.0.RELEASE</version>  
  6.     </dependency>  
  7.   </dependencies>  

 

Main.java

Java代码  收藏代码
  1. package stephansun.github.samples.spring.remoting;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class Main {  
  9.   
  10.     public static void main(String[] args) {  
  11.         ClassPathXmlApplicationContext applicationContext =  
  12.                 new ClassPathXmlApplicationContext(new String[] {  
  13.                         "stephansun/github/samples/spring/remoting/spring-remoting.xml"  
  14.                 });  
  15.           
  16.         MyService myService = (MyService) applicationContext.getBean("sender");  
  17.           
  18.         Map<String, Object> param = new HashMap<String, Object>();  
  19.         param.put("name""stephan");  
  20.         param.put("age"26);  
  21.         String str = myService.foo(param);  
  22.         System.out.println("str:" + str);  
  23.     }  
  24. }   

  MyInvokerClientInterceptor.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.spring.remoting;  
  2.   
  3. import org.aopalliance.intercept.MethodInterceptor;  
  4. import org.aopalliance.intercept.MethodInvocation;  
  5. import org.springframework.beans.factory.InitializingBean;  
  6. import org.springframework.remoting.support.DefaultRemoteInvocationFactory;  
  7. import org.springframework.remoting.support.RemoteInvocation;  
  8. import org.springframework.remoting.support.RemoteInvocationFactory;  
  9. import org.springframework.remoting.support.RemoteInvocationResult;  
  10.   
  11. public class MyInvokerClientInterceptor implements MethodInterceptor, InitializingBean {  
  12.       
  13.     private RemoteInvocationFactory remoteInvocationFactory = new DefaultRemoteInvocationFactory();  
  14.       
  15.     public void setRemoteInvocationFactory(RemoteInvocationFactory remoteInvocationFactory) {  
  16.         this.remoteInvocationFactory =  
  17.                 (remoteInvocationFactory != null ? remoteInvocationFactory : new DefaultRemoteInvocationFactory());  
  18.     }  
  19.       
  20.     protected RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {  
  21.         return this.remoteInvocationFactory.createRemoteInvocation(methodInvocation);  
  22.     }  
  23.   
  24.     @Override  
  25.     public void afterPropertiesSet() throws Exception {  
  26.         System.out.println("afterPropertiesSet");  
  27.     }  
  28.   
  29.     @Override  
  30.     public Object invoke(MethodInvocation methodInvocation) throws Throwable {  
  31.         RemoteInvocation invocation = createRemoteInvocation(methodInvocation);  
  32.         Object[] arguments = invocation.getArguments();  
  33.         System.out.println("arguments:" + arguments);  
  34.         String methodName = invocation.getMethodName();  
  35.         System.out.println("methodName:" + methodName);  
  36.         Class[] classes = invocation.getParameterTypes();  
  37.         System.out.println("classes:" + classes);  
  38.         // do whatever you want to do  
  39.         RemoteInvocationResult result = new RemoteInvocationResult("hello, world!");  
  40.         return result.getValue();  
  41.     }  
  42.   
  43. }  

 

 MyInvokerProxyFactoryBean.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.spring.remoting;  
  2.   
  3. import org.springframework.aop.framework.ProxyFactory;  
  4. import org.springframework.beans.factory.BeanClassLoaderAware;  
  5. import org.springframework.beans.factory.FactoryBean;  
  6. import org.springframework.util.ClassUtils;  
  7.   
  8. public class MyInvokerProxyFactoryBean extends MyInvokerClientInterceptor  
  9.     implements FactoryBean<Object>, BeanClassLoaderAware {  
  10.       
  11.     private Class serviceInterface;  
  12.   
  13.     private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();  
  14.   
  15.     private Object serviceProxy;  
  16.   
  17.     // FIXME for Spring injection  
  18.     public void setServiceInterface(Class serviceInterface) {  
  19.         this.serviceInterface = serviceInterface;  
  20.     }  
  21.   
  22.     public void afterPropertiesSet() throws Exception {  
  23.         super.afterPropertiesSet();  
  24.         if (this.serviceInterface == null) {  
  25.             throw new IllegalArgumentException("Property 'serviceInterface' is required");  
  26.         }  
  27.         this.serviceProxy = new ProxyFactory(this.serviceInterface, this).getProxy(this.beanClassLoader);  
  28.     }  
  29.   
  30.     @Override  
  31.     public void setBeanClassLoader(ClassLoader classLoader) {  
  32.         this.beanClassLoader = classLoader;  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object getObject() throws Exception {  
  37.         return this.serviceProxy;  
  38.     }  
  39.   
  40.     @Override  
  41.     public Class<?> getObjectType() {  
  42.         return this.serviceInterface;  
  43.     }  
  44.   
  45.     @Override  
  46.     public boolean isSingleton() {  
  47.         return true;  
  48.     }  
  49.   
  50. }  

 

MyService.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.spring.remoting;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public interface MyService {  
  6.   
  7.     void sayHello();  
  8.       
  9.     String foo(Map<String, Object> param);  
  10.       
  11. }  

 

 spring-remoting.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="sender"  
  12.         class="stephansun.github.samples.spring.remoting.MyInvokerProxyFactoryBean">  
  13.         <property name="serviceInterface" value="stephansun.github.samples.spring.remoting.MyService"/>  
  14.     </bean>  
  15.           
  16. </beans>  

 

 从输出的结果可以看出,Spring将接口的参数,调用方法,类名字封装到RemoteInvocation类中,这个类是序列的,意味着它可以自由地以字节形式在网络上传输,jms,http,amqp都支持字节形式地消息传输,所以我们能基于接口远程方法调用,无论你采用那种网络传输协议。

samples-jms-plain

pom.xml

 

Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.apache.activemq</groupId>  
  4.         <artifactId>activemq-all</artifactId>  
  5.         <version>5.3.0</version>  
  6.     </dependency>  
  7.   </dependencies>  

 

 point-to-point

Receiver.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.plain.pointtopoint;  
  2.   
  3. import javax.jms.Connection;  
  4. import javax.jms.ConnectionFactory;  
  5. import javax.jms.Destination;  
  6. import javax.jms.JMSException;  
  7. import javax.jms.Message;  
  8. import javax.jms.MessageConsumer;  
  9. import javax.jms.Session;  
  10. import javax.jms.TextMessage;  
  11.   
  12. import org.apache.activemq.ActiveMQConnectionFactory;  
  13. import org.apache.activemq.command.ActiveMQQueue;  
  14.   
  15. public class Receiver {  
  16.   
  17.     public static void main(String[] args) {  
  18.         // 获得连接工厂  
  19.         ConnectionFactory cf = new ActiveMQConnectionFactory(  
  20.                 "tcp://localhost:61616");  
  21.           
  22.         // javax.jms.Connection  
  23.         Connection conn = null;  
  24.         // javax.jms.Session  
  25.         Session session = null;  
  26.           
  27.         try {  
  28.             // 创建连接  
  29.             conn = cf.createConnection();  
  30.               
  31.             // 创建会话  
  32.             session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  33.               
  34.             // 选择目标  
  35.             Destination destination = new ActiveMQQueue("myQueue");  
  36.               
  37.             //   
  38.             MessageConsumer consumer = session.createConsumer(destination);  
  39.               
  40.             conn.start();  
  41.               
  42.             // 接收消息  
  43.             Message message = consumer.receive();  
  44.               
  45.             TextMessage textMessage = (TextMessage) message;  
  46.             System.out.println("得到一个消息:" + textMessage.getText());  
  47.         } catch (JMSException e) {  
  48.             // 处理异常  
  49.             e.printStackTrace();  
  50.         } finally {  
  51.             try {  
  52.                 // 清理资源  
  53.                 if (session != null) {  
  54.                     session.close();  
  55.                 }  
  56.                 if (conn != null) {  
  57.                     conn.close();  
  58.                 }  
  59.             } catch (JMSException ex) {  
  60.                 ex.printStackTrace();  
  61.             }  
  62.         }  
  63.     }  
  64.       
  65. }  

 

 Sender.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.plain.pointtopoint;  
  2.   
  3. import javax.jms.Connection;  
  4. import javax.jms.ConnectionFactory;  
  5. import javax.jms.Destination;  
  6. import javax.jms.JMSException;  
  7. import javax.jms.MessageProducer;  
  8. import javax.jms.Session;  
  9. import javax.jms.TextMessage;  
  10.   
  11. import org.apache.activemq.ActiveMQConnectionFactory;  
  12. import org.apache.activemq.command.ActiveMQQueue;  
  13.   
  14. public class Sender {  
  15.   
  16.     public static void main(String[] args) {  
  17.         // 获得连接工厂  
  18.         ConnectionFactory cf = new ActiveMQConnectionFactory(  
  19.                 "tcp://localhost:61616");  
  20.           
  21.         // javax.jms.Connection  
  22.         Connection conn = null;  
  23.         // javax.jms.Session  
  24.         Session session = null;  
  25.           
  26.         try {  
  27.             // 创建连接  
  28.             conn = cf.createConnection();  
  29.               
  30.             // 创建会话  
  31.             session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  32.               
  33.             // 创建队列  
  34.             Destination destination = new ActiveMQQueue("myQueue");  
  35.               
  36.             // 设置消息  
  37.             MessageProducer producer = session.createProducer(destination);  
  38.             TextMessage message = session.createTextMessage();  
  39.             message.setText("Hello World!");  
  40.               
  41.             producer.send(message);  
  42.         } catch (JMSException e) {  
  43.             // 处理异常  
  44.             e.printStackTrace();  
  45.         } finally {  
  46.             try {  
  47.                 // 清理资源  
  48.                 if (session != null) {  
  49.                     session.close();  
  50.                 }  
  51.                 if (conn != null) {  
  52.                     conn.close();  
  53.                 }  
  54.             } catch (JMSException ex) {  
  55.                 ex.printStackTrace();  
  56.             }  
  57.         }  
  58.     }  
  59.       
  60. }  

 

 publish-subscribe

Receiver1.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.plain.pubsub;  
  2.   
  3. import javax.jms.Connection;  
  4. import javax.jms.ConnectionFactory;  
  5. import javax.jms.Destination;  
  6. import javax.jms.JMSException;  
  7. import javax.jms.Message;  
  8. import javax.jms.MessageConsumer;  
  9. import javax.jms.Session;  
  10. import javax.jms.TextMessage;  
  11.   
  12. import org.apache.activemq.ActiveMQConnectionFactory;  
  13. import org.apache.activemq.command.ActiveMQTopic;  
  14.   
  15. public class Receiver1 {  
  16.   
  17.     public static void main(String[] args) {  
  18.         // 获得连接工厂  
  19.         ConnectionFactory cf = new ActiveMQConnectionFactory(  
  20.                 "tcp://localhost:61616");  
  21.           
  22.         // javax.jms.Connection  
  23.         Connection conn = null;  
  24.         // javax.jms.Session  
  25.         Session session = null;  
  26.           
  27.         try {  
  28.             // 创建连接  
  29.             conn = cf.createConnection();  
  30.               
  31.             // 创建会话  
  32.             session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  33.               
  34.             // 选择目标  
  35.             Destination destination = new ActiveMQTopic("myTopic");  
  36.               
  37.             //   
  38.             MessageConsumer consumer = session.createConsumer(destination);  
  39.               
  40.             conn.start();  
  41.               
  42.             // 接收消息  
  43.             Message message = consumer.receive();  
  44.               
  45.             TextMessage textMessage = (TextMessage) message;  
  46.             System.out.println("接收者1 得到一个消息:" + textMessage.getText());  
  47.         } catch (JMSException e) {  
  48.             // 处理异常  
  49.             e.printStackTrace();  
  50.         } finally {  
  51.             try {  
  52.                 // 清理资源  
  53.                 if (session != null) {  
  54.                     session.close();  
  55.                 }  
  56.                 if (conn != null) {  
  57.                     conn.close();  
  58.                 }  
  59.             } catch (JMSException ex) {  
  60.                 ex.printStackTrace();  
  61.             }  
  62.         }  
  63.     }  
  64.       
  65. }  

 

 Sender.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.plain.pubsub;  
  2.   
  3. import javax.jms.Connection;  
  4. import javax.jms.ConnectionFactory;  
  5. import javax.jms.Destination;  
  6. import javax.jms.JMSException;  
  7. import javax.jms.MessageProducer;  
  8. import javax.jms.Session;  
  9. import javax.jms.TextMessage;  
  10.   
  11. import org.apache.activemq.ActiveMQConnectionFactory;  
  12. import org.apache.activemq.command.ActiveMQTopic;  
  13.   
  14. public class Sender {  
  15.   
  16.     public static void main(String[] args) {  
  17.         // 获得连接工厂  
  18.         ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");  
  19.           
  20.         // javax.jms.Connection  
  21.         Connection conn = null;  
  22.         // javax.jms.Session  
  23.         Session session = null;  
  24.           
  25.         try {  
  26.             // 创建连接  
  27.             conn = cf.createConnection();  
  28.               
  29.             // 创建会话  
  30.             session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);  
  31.               
  32.             // 创建队列  
  33.             Destination destination = new ActiveMQTopic("myTopic");  
  34.               
  35.             // 设置消息  
  36.             MessageProducer producer = session.createProducer(destination);  
  37.             TextMessage message = session.createTextMessage();  
  38.             message.setText("Hello World!");  
  39.               
  40.             producer.send(message);  
  41.         } catch (JMSException e) {  
  42.             // 处理异常  
  43.             e.printStackTrace();  
  44.         } finally {  
  45.             try {  
  46.                 // 清理资源  
  47.                 if (session != null) {  
  48.                     session.close();  
  49.                 }  
  50.                 if (conn != null) {  
  51.                     conn.close();  
  52.                 }  
  53.             } catch (JMSException ex) {  
  54.                 ex.printStackTrace();  
  55.             }  
  56.         }  
  57.     }  
  58.       
  59. }  

 

samples-jms-spring

pom.xml

 

Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.apache.activemq</groupId>  
  4.         <artifactId>activemq-all</artifactId>  
  5.         <version>5.3.0</version>  
  6.     </dependency>  
  7.     <dependency>  
  8.         <groupId>org.springframework</groupId>  
  9.         <artifactId>spring-jms</artifactId>  
  10.         <version>3.1.0.RELEASE</version>  
  11.     </dependency>  
  12.   </dependencies>  

 point-to-point

 

Receiver.java

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.pointtopoint;  
  2.   
  3. import javax.jms.JMSException;  
  4. import javax.jms.MapMessage;  
  5. import javax.jms.Queue;  
  6.   
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8. import org.springframework.jms.core.JmsTemplate;  
  9.   
  10. public class Receiver {  
  11.   
  12.     public static void main(String[] args) throws JMSException {  
  13.         ClassPathXmlApplicationContext applicationContext =  
  14.                 new ClassPathXmlApplicationContext(  
  15.                         "stephansun/github/samples/jms/spring/pointtopoint/jms-point-to-point.xml");  
  16.           
  17.         Queue myQueue = (Queue) applicationContext.getBean("myQueue");  
  18.         JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");  
  19.           
  20.         MapMessage message = (MapMessage) jmsTemplate.receive(myQueue);  
  21.           
  22.         String name = message.getString("name");  
  23.         int age = message.getInt("age");  
  24.           
  25.         System.out.println("name:" + name);  
  26.         System.out.println("age:" + age);  
  27.     }  
  28.       
  29. }   

  Sender.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.pointtopoint;  
  2.   
  3. import javax.jms.JMSException;  
  4. import javax.jms.MapMessage;  
  5. import javax.jms.Message;  
  6. import javax.jms.Queue;  
  7. import javax.jms.Session;  
  8.   
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10. import org.springframework.jms.core.JmsTemplate;  
  11. import org.springframework.jms.core.MessageCreator;  
  12.   
  13. public class Sender {  
  14.   
  15.     public static void main(String[] args) {  
  16.         ClassPathXmlApplicationContext applicationContext =  
  17.                 new ClassPathXmlApplicationContext(  
  18.                         "stephansun/github/samples/jms/spring/pointtopoint/jms-point-to-point.xml");  
  19.           
  20.         Queue myQueue = (Queue) applicationContext.getBean("myQueue");  
  21.         JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");  
  22.           
  23.         jmsTemplate.send(myQueue, new MessageCreator() {  
  24.             @Override  
  25.             public Message createMessage(Session session) throws JMSException {  
  26.                 MapMessage message = session.createMapMessage();  
  27.                 message.setString("name""stephan");  
  28.                 message.setInt("age"26);  
  29.                 return message;  
  30.             }  
  31.         });  
  32.     }  
  33.       
  34. }  

 

 jms-point-to-point.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="connectionFactory"  
  12.         class="org.apache.activemq.ActiveMQConnectionFactory"/>  
  13.           
  14.     <bean id="myQueue"  
  15.         class="org.apache.activemq.command.ActiveMQQueue">  
  16.         <constructor-arg index="0" value="myQueue"/>    
  17.     </bean>  
  18.           
  19.     <bean id="jmsTemplate"  
  20.         class="org.springframework.jms.core.JmsTemplate">  
  21.         <property name="connectionFactory" ref="connectionFactory"/>    
  22.     </bean>  
  23.           
  24. </beans>  

 

 publish-subscribe

Receiver1.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.pubsub;  
  2.   
  3. import javax.jms.JMSException;  
  4. import javax.jms.MapMessage;  
  5. import javax.jms.Topic;  
  6.   
  7. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  8. import org.springframework.jms.core.JmsTemplate;  
  9.   
  10. public class Receiver1 {  
  11.   
  12.     public static void main(String[] args) throws JMSException {  
  13.         ClassPathXmlApplicationContext applicationContext =  
  14.                 new ClassPathXmlApplicationContext(  
  15.                         "stephansun/github/samples/jms/spring/pubsub/jms-pub-sub.xml");  
  16.           
  17.         Topic myTopic = (Topic) applicationContext.getBean("myTopic");  
  18.         JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");  
  19.           
  20.         MapMessage message = (MapMessage) jmsTemplate.receive(myTopic);  
  21.           
  22.         String name = message.getString("name");  
  23.         int age = message.getInt("age");  
  24.           
  25.         System.out.println("name:" + name);  
  26.         System.out.println("age:" + age);  
  27.     }  
  28.       
  29. }  

 

 Sender.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.pubsub;  
  2.   
  3. import javax.jms.JMSException;  
  4. import javax.jms.MapMessage;  
  5. import javax.jms.Message;  
  6. import javax.jms.Session;  
  7. import javax.jms.Topic;  
  8.   
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10. import org.springframework.jms.core.JmsTemplate;  
  11. import org.springframework.jms.core.MessageCreator;  
  12.   
  13. public class Sender {  
  14.   
  15.     public static void main(String[] args) {  
  16.         ClassPathXmlApplicationContext applicationContext =  
  17.                 new ClassPathXmlApplicationContext(  
  18.                         "stephansun/github/samples/jms/spring/pubsub/jms-pub-sub.xml");  
  19.           
  20.         Topic myTopic = (Topic) applicationContext.getBean("myTopic");  
  21.         JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");  
  22.           
  23.         jmsTemplate.send(myTopic, new MessageCreator() {  
  24.             @Override  
  25.             public Message createMessage(Session session) throws JMSException {  
  26.                 MapMessage message = session.createMapMessage();  
  27.                 message.setString("name""stephan");  
  28.                 message.setInt("age"26);  
  29.                 return message;  
  30.             }  
  31.         });  
  32.     }  
  33.       
  34. }  

 

 jms-pub-sub.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="connectionFactory"  
  12.         class="org.apache.activemq.ActiveMQConnectionFactory"/>  
  13.           
  14.     <bean id="myTopic"  
  15.         class="org.apache.activemq.command.ActiveMQTopic">  
  16.         <constructor-arg index="0" value="myTopic"/>    
  17.     </bean>  
  18.           
  19.     <bean id="jmsTemplate"  
  20.         class="org.springframework.jms.core.JmsTemplate">  
  21.         <property name="connectionFactory" ref="connectionFactory"/>    
  22.     </bean>  
  23.           
  24. </beans>  

 

 samples-jms-spring-remoting

pom.xml

 

Xml代码  收藏代码
  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>org.apache.activemq</groupId>  
  4.         <artifactId>activemq-all</artifactId>  
  5.         <version>5.3.0</version>  
  6.     </dependency>  
  7.     <dependency>  
  8.         <groupId>org.springframework</groupId>  
  9.         <artifactId>spring-jms</artifactId>  
  10.         <version>3.1.0.RELEASE</version>  
  11.     </dependency>  
  12.   </dependencies>  

 

 Main.java

 

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.remoting;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  7.   
  8. public class Main {  
  9.   
  10.     public static void main(String[] args) {  
  11.         ClassPathXmlApplicationContext applicationContext =  
  12.                 new ClassPathXmlApplicationContext(new String[] {  
  13.                         "stephansun/github/samples/jms/spring/remoting/jms-remoting.xml",  
  14.                         "stephansun/github/samples/jms/spring/remoting/jms-remoting-sender.xml",  
  15.                         "stephansun/github/samples/jms/spring/remoting/jms-remoting-receiver.xml"  
  16.                 });  
  17.         MyService sender = (MyService) applicationContext.getBean("sender");  
  18.         sender.sayHello();  
  19.           
  20.         Map<String, Object> param = new HashMap<String, Object>();  
  21.         param.put("name""stephan");  
  22.         param.put("age"26);  
  23.         String str = sender.foo(param);  
  24.         System.out.println("str:" + str);  
  25.     }  
  26. }  

 

MyService.java

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.remoting;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public interface MyService {  
  6.   
  7.     void sayHello();  
  8.       
  9.     String foo(Map<String, Object> param);  
  10.       
  11. }   

MyServiceImpl.java

Java代码  收藏代码
  1. package stephansun.github.samples.jms.spring.remoting;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public class MyServiceImpl implements MyService {  
  6.   
  7.     @Override  
  8.     public void sayHello() {  
  9.         System.out.println("hello world!");  
  10.     }  
  11.   
  12.     @Override  
  13.     public String foo(Map<String, Object> param) {  
  14.         return param.toString();  
  15.     }  
  16.   
  17. }   

jms-remoting-receiver.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="myService"  
  12.         class="stephansun.github.samples.jms.spring.remoting.MyServiceImpl"/>  
  13.       
  14.     <bean id="receiver"  
  15.         class="org.springframework.jms.remoting.JmsInvokerServiceExporter">  
  16.         <property name="serviceInterface" value="stephansun.github.samples.jms.spring.remoting.MyService"/>  
  17.         <property name="service" ref="myService"/>  
  18.     </bean>  
  19.       
  20.     <bean id="container"  
  21.         class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
  22.         <property name="connectionFactory" ref="connectionFactory"/>  
  23.         <property name="messageListener" ref="receiver"/>  
  24.         <property name="destination" ref="myQueue"/>    
  25.     </bean>  
  26.           
  27. </beans>  

    jms-remoting-sender.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="sender"  
  12.         class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean">  
  13.         <property name="connectionFactory" ref="connectionFactory"/>  
  14.         <property name="queue" ref="myQueue"/>  
  15.         <property name="serviceInterface" value="stephansun.github.samples.jms.spring.remoting.MyService"/>  
  16.         <property name="receiveTimeout" value="5000"/>  
  17.     </bean>  
  18.           
  19. </beans>  

 

 jms-remoting.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">  
  10.   
  11.     <bean id="connectionFactory"  
  12.         class="org.apache.activemq.ActiveMQConnectionFactory"/>  
  13.           
  14.     <bean id="myQueue"  
  15.         class="org.apache.activemq.command.ActiveMQQueue">  
  16.         <constructor-arg index="0" value="myQueue"/>    
  17.     </bean>  
  18.           
  19.     <bean id="jmsTemplate"  
  20.         class="org.springframework.jms.core.JmsTemplate">  
  21.         <property name="connectionFactory" ref="connectionFactory"/>    
  22.     </bean>  
  23.           
  24. </beans>  

 

 JMS跟AMQP有很大的区别,JMS有两种类型的队列,一个是点对点的,一种是主题订阅的,发送者直接将消息发送至队列,接受者从队列收消息,对于发布订阅模式,每个消费者都从队列中得到了相同的消息拷贝。


2 0
原创粉丝点击