JMS、AMQP实例讲解

  • 使用Git从GitHub上将samples代码拷贝到本机,然后导入到IDE中
Shell代码 复制代码  收藏代码
  1. git clone git://github.com/stephansun/samples.git  
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>  
<dependencies>
 	<dependency>
		<groupId>com.rabbitmq</groupId>
		<artifactId>amqp-client</artifactId>
		<version>2.5.0</version>
		<exclusions>
			<exclusion>
				<groupId>commons-cli</groupId>
				<artifactId>commons-cli</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
  </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  
com.rabbitmq.client.BasicProperties
com.rabbitmq.client.Channel
com.rabbitmq.client.Connection
com.rabbitmq.client.ConnectionFactory
com.rabbitmq.client.Consumer
com.rabbitmq.client.MessageProperties
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. }  
package stephansun.github.samples.amqp.plain.helloworld;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Send {

	private final static String QUEUE_NAME = "hello";
	
	public static void main(String[] args) throws IOException {
		// AMQP的连接其实是对Socket做的封装, 注意以下AMQP协议的版本号,不同版本的协议用法可能不同。
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		// 下一步我们创建一个channel, 通过这个channel就可以完成API中的大部分工作了。
		Channel channel = connection.createChannel();
		
		// 为了发送消息, 我们必须声明一个队列,来表示我们的消息最终要发往的目的地。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		String message = "Hello World!";
		// 然后我们将一个消息发往这个队列。
		channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
		System.out.println("[" + message + "]");
		
		// 最后,我们关闭channel和连接,释放资源。
		channel.close();
		connection.close();
	}
}
 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. }  
package stephansun.github.samples.amqp.plain.helloworld;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class Recv {

	private final static String QUEUE_NAME = "hello";
	
	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		// 注意我们也在这里声明了一个queue,因为我们有可能在发送者启动前先启动接收者。
		// 我们要确保当从这个queue消费消息时,这个queue是存在的。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("CRTL+C");
		
		// 这个另外的QueueingConsumer类用来缓存服务端推送给我们的消息。
		// 下面我们准备告诉服务端给我们传递存放在queue里的消息,因为消息是由服务端推送过来的。
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(QUEUE_NAME, true, consumer);
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			System.out.println("[" + message + "]");
		}
	}
}
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. }  
package stephansun.github.samples.amqp.plain.workqueues;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class Worker {

	private final static String QUEUE_NAME = "task_queue";
	
	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("CRTL+C");
		
		// 这条语句告诉RabbitMQ在同一时间不要给一个worker一个以上的消息。
		// 或者换一句话说, 不要将一个新的消息分发给worker知道它处理完了并且返回了前一个消息的通知标志(acknowledged)
		// 替代的,消息将会分发给下一个不忙的worker。
		channel.basicQos(1);
		
		QueueingConsumer consumer = new QueueingConsumer(channel);
		// 自动通知标志
		boolean autoAck = false;
		channel.basicConsume(QUEUE_NAME, autoAck, consumer);
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			System.out.println("r[" + message + "]");
			doWord(message);
			System.out.println("r[done]");
			// 发出通知标志
			channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
		}
	}

	private static void doWord(String task) throws InterruptedException {
		for (char ch : task.toCharArray()) {
			if (ch == '.') {
				Thread.sleep(1000);
			}
		}
	}
}
在本代码中,
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.  
Parameters:
deliveryTag the tag from the received com.rabbitmq.client.AMQP.Basic.GetOk or com.rabbitmq.client.AMQP.Basic.Deliver
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. }  
package stephansun.github.samples.amqp.plain.workqueues;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

public class NewTask {
	
	// 使用Work Queues (也称为Task Queues)最主要的想法是分流那些耗时,耗资源的任务,不至于使队列拥堵。 

	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
	
	private final static String QUEUE_NAME = "task_queue";
	
	public static void main(String[] args) throws IOException {
		String[] strs = new String[] { "First message." };
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		// 跟helloworld的不同点
		boolean durable = true;
		// 下面这个声明队列的队列名字改了,所以生产者和消费者两边的程序都要改成统一的队列名字。
		channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
		// 有了durable为true,我们可以保证名叫task_queue的队列即使在RabbitMQ重启的情况下也不会消失。
		String message = getMessage(strs);
		// 现在我们需要将消息标记成可持久化的。
		// 如果你需要更强大的保证消息传递,你可以将发布消息的代码打包到一个事务里。 
		channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
		System.out.println("s[" + message + "]");
		
		channel.close();
		connection.close();
	}
}

 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. }  
package stephansun.github.samples.amqp.plain.publishsubscribe;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLog {
	
	// 在前面,我们使用queue,都给定了一个指定的名字。能够对一个queue命名对于我们来说是很严肃的
	// 下面我们需要将worker指定到同一个queue。
	
	// echange的类型有: direct, topic, headers and fanout.

	private static final String EXCHANGE_NAME = "logs";
	
	public static void main(String[] args) throws IOException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		// fanout exchange 将它收的所有消息广播给它知道的所有队列。
		channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
		
		String message = getMessage(new String[] { "test" });
		
		// 如果routingkey存在的话,消息通过一个routingkey指定的名字路由至队列
		channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
		System.out.println("sent [" + message + "]");
		
		channel.close();
		connection.close();
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}
 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. }  
package stephansun.github.samples.amqp.plain.publishsubscribe;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class ReceiveLogs {
	
	// 就像你看到的, 创建了连接后,我们声明了一个exchange,这一步是必须的,因为将消息发送到一个并不存在的exchange上是不允许的。
	// 如果还没有queue绑定到exchange上,消息将会丢失。
	// 但那对我们来说是ok的。
	// 如果没有消费者在监听,我们可以安全地丢弃掉消息。
	
	// RabbitMQ中有关消息模型地核心观点是,生产者永远不会直接将消息发往队列。
	// 事实上,相当多的生产者甚至根本不知道一个消息是否已经传递给了一个队列。
	// 相反,生产者只能将消息发送给一个exchange。
	// exchange是一个很简单的东西。
	// 一边它接收来自生产者的消息,另一边它将这些消息推送到队列。
	// exchagne必须明确地知道拿它收到的消息来做什么。把消息附在一个特定的队列上?把消息附在很多队列上?或者把消息丢弃掉。
	// 这些规则在exchange类型里都有定义。

	private static final String EXCHANGE_NAME = "logs";
	
	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		// 创建fanout类型的exchange, 我们叫它logs:
		// 这种类型的exchange将它收到的所有消息广播给它知道的所有队列。
		channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
		// 临时队列(temporary queue)
		// 首先,无论什么时候连接Rabbit时,我们需要一个fresh的,空的队列
		// First, whenever we connect to Rabbit we need a fresh, empty queue.
		// 为了做到这一点,我们可以创建一个随机命名的队列,或者更好的,就让服务端给我们选择一个随机的队列名字。
		// 其次,一旦我们关闭消费者的连接,这个临时队列应该自动销毁。
		String queueName = channel.queueDeclare().getQueue();
		channel.queueBind(queueName, EXCHANGE_NAME, "");
		
		System.out.println("CTRL+C");
		
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(queueName, true, consumer);
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			
			System.out.println("r[" + message + "]");
		}
	}	
}
 发布订阅,本代码演示的是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. }  
package stephansun.github.samples.amqp.plain.routing;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLogDirect {

	private static final String EXCHANGE_NAME = "direct_logs";
	
	public static void main(String[] args) throws IOException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		channel.exchangeDeclare(EXCHANGE_NAME, "direct");
		
		// diff
		String serverity = getServerity(new String[] { "test" });
		String message = getMessage(new String[] { "test" });
		
		channel.basicPublish(EXCHANGE_NAME, serverity, null, message.getBytes());
		System.out.println("s[" + serverity + "]:[" + message + "]");
		
		channel.close();
		connection.close();
		
	}

	private static String getServerity(String[] strings) {
		return "info";
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}
 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. }  
package stephansun.github.samples.amqp.plain.routing;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class ReceiveLogsDirect {

	private static final String EXCHANGE_NAME = "direct_logs";
	
	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		channel.exchangeDeclare(EXCHANGE_NAME, "direct");
		String queueName = channel.queueDeclare().getQueue();
		
		String[] strs = new String[] { "info", "waring", "error" };
		for (String str : strs) {
			channel.queueBind(queueName, EXCHANGE_NAME, str);
		}
		
		System.out.println("CTRL+C");
		
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(queueName, true, consumer);
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			String routingKey = delivery.getEnvelope().getRoutingKey();
			
			System.out.println("r:[" + routingKey + "]:[" + message + "]");
		}
	}
}
 本代码演示了另外一种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. }  
package stephansun.github.samples.amqp.plain.topics;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLogTopic {

	private static final String EXCHANGE_NAME = "topic_logs";
	
	public static void main(String[] args) throws IOException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		channel.exchangeDeclare(EXCHANGE_NAME, "topic");
		
		// diff
		String routingKey = getServerity(new String[] { "test" });
		String message = getMessage(new String[] { "test" });
		
		channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
		System.out.println("s[" + routingKey + "]:[" + message + "]");
		
		channel.close();
		connection.close();
		
	}

	private static String getServerity(String[] strings) {
		return "kern.critical";
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}
 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. }  
package stephansun.github.samples.amqp.plain.topics;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class ReceiveLogsTopic {
	
	// FIXME
	// Some teasers:
	// Will "*" binding catch a message sent with an empty routing key?
	// Will "#.*" catch a message with a string ".." as a key? Will it catch a message with a single word key?
	// How different is "a.*.#" from "a.#"?

	private static final String EXCHANGE_NAME = "topic_logs";
	
	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		
		channel.exchangeDeclare(EXCHANGE_NAME, "topic");
		String queueName = channel.queueDeclare().getQueue();
		
		String[] strs = new String[] { "kern.critical", "A critical kernel error" };
		for (String str : strs) {
			channel.queueBind(queueName, EXCHANGE_NAME, str);
		}
		
		System.out.println("CTRL+C");
		
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(queueName, true, consumer);
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			String routingKey = delivery.getEnvelope().getRoutingKey();
			
			System.out.println("r:[" + routingKey + "]:[" + message + "]");
		}
	}
}
 本代码演示了最后一种类型的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. }  
package stephansun.github.samples.amqp.plain.rpc;

import java.io.IOException;
import java.util.UUID;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class RPCClient {
	
	// FIXME
	// AMQP协议预定义了14种伴随着消息的属性。大多数属性很少使用到。除了以下这些异常情况:
	// deliveryMode:
	// contentType:
	// replyTo:
	// correlationId: 
	
	// FIXME
	// 为什么我们忽略掉callback队列里的消息,而不是抛出错误?
	// 这取决于服务端的竞争条件的可能性。
	// 虽然不太可能,但这种情况是存在的,即
	// RPC服务在刚刚将答案发给我们,然而没等我们将通知标志后返回时就死了
	// 如果发生了这种情况, 重启的RPC服务将会重新再次处理该请求。
	// 这就是为什么在客户端我们必须优雅地处理重复性的响应,及RPC在理想情况下应该时幂等的。(不太理解这句话的意思)

	private Connection connection;
	private Channel channel;
	private String requestQueueName = "rpc_queue";
	private String replyQueueName;
	private QueueingConsumer consumer;
	
	public RPCClient() throws IOException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		connection = factory.newConnection();
		channel = connection.createChannel();
		
		// temporary queue.
		replyQueueName = channel.queueDeclare().getQueue();
		consumer = new QueueingConsumer(channel);
		channel.basicConsume(replyQueueName, true, consumer);
	}
	
	public String call(String message) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		String response = null;
		String corrId = UUID.randomUUID().toString();
		
		// in order to receive a response we need to send a 'callback' queue address with the request.
		// We can use the default queue(which is exclusive in the Java client)
		BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();
		
		channel.basicPublish("", requestQueueName, props, message.getBytes());
		
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			if (delivery.getProperties().getCorrelationId().equals(corrId)) {
				response = new String(delivery.getBody(), "UTF-8");
				break;
			}
		}
		
		return response;
	}
	
	public void close() throws IOException {
		connection.close();
	}
	
	public static void main(String[] args) {
		RPCClient fibonacciRpc = null;
		String response = null;
		try {
			fibonacciRpc = new RPCClient();
			
			System.out.println("fib(30)");
			response = fibonacciRpc.call("30");
			System.out.println("got[" + response + "]");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fibonacciRpc != null) {
				try {
					fibonacciRpc.clone();
				} catch (Exception ignore) {
					// ignore
				}
			}
		}
	}
}
 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. }  
package stephansun.github.samples.amqp.plain.rpc;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class RPCServer {

	// 我们的代码仍然相当简单,没有试图解决更复杂(或者更重要)的问题,像:
	// 客户端在没有服务端运行的情况下如何处理?
	// 一个RPC的客户端应该有一些超时类型吗?
	// 如果服务端出现异常,是否应该将异常返回给客户端?
	// 在进行业务处理前阻止不合法的消息进入(比如检查绑定,类型)
	// Protecting against invalid incoming messages (eg checking bounds, type) before processing.

	private static final String RPC_QUEUE_NAME = "rpc_queue";
	
	// FIXME Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible.
	private static int fib(int n) {
		if (n == 0) {
			return 0;
		}
		if (n == 1) {
			return 1;
		}
		return fib(n - 1) + fib(n - 2);
	}
	
	public static void main(String[] args) {
		Connection connection = null;
		Channel channel = null;
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			
			connection = factory.newConnection();
			channel = connection.createChannel();
			
			channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
			
			// We might want to run more than one server process. 
			// In order to spread the load equally over multiple servers we need to set the prefetchCount setting in channel.basicQos.
			channel.basicQos(1);
			
			QueueingConsumer consumer = new QueueingConsumer(channel);
			channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
			
			System.out.println("[x] Awaiting RPC requests");
			
			while (true) {
				String response = null;
				
				QueueingConsumer.Delivery delivery = consumer.nextDelivery();
				
				BasicProperties props = delivery.getProperties();
				BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
				
				try {
					String message = new String(delivery.getBody(), "UTF-8");
					int n = Integer.parseInt(message);
					
					System.out.println(" [.] fib(" + message + ")");
					response = "" + fib(n);
				} catch (Exception e) {
					System.out.println(" [.] " + e.toString());
					response = "";
				} finally {
					channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
					
					channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception ignore) {
					// ignore
				}
			}
		}
	}
}
 本代码实现了一个简单的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>  
<dependencies>
  	<dependency>
  		<groupId>org.springframework.amqp</groupId>
  		<artifactId>spring-amqp-rabbit</artifactId>
  		<version>1.0.0.RC1</version>
  	</dependency>
  </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  
org.springframework.amqp.AmqpTemplate
org.springframework.amqp.Binding
org.springframework.amqp.DirectExchange
org.springframework.amqp.FanoutExchange
org.springframework.amqp.TopicExchange
org.springframework.amqp.Message
org.springframework.amqp.MessageListener
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. }  
package stephansun.github.samples.amqp.spring.helloworld;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Send {

	private final static String QUEUE_NAME = "hello";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/helloworld/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		String message = "Hello World!";
		
		rabbitTempalte.send("", QUEUE_NAME, messageConverter.toMessage(message, null));
	}
	
}
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. }   
package stephansun.github.samples.amqp.spring.helloworld;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Recv {

	private final static String QUEUE_NAME = "hello";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/helloworld/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		Message message = rabbitTempalte.receive(QUEUE_NAME);
		
		Object obj = messageConverter.fromMessage(message);
		
		System.out.println("received:[" + obj + "]");
		
	}
} 
  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 version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<rabbit:queue name="hello"
		durable="false"
		exclusive="false"
		auto-delete="false"/>
		
</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. }  
package stephansun.github.samples.amqp.spring.workqueues;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

import com.rabbitmq.client.Channel;

public class MyWorker implements ChannelAwareMessageListener {

	private void doWord(String task) {
		for (char ch : task.toCharArray()) {
			if (ch == '.') {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		throw new RuntimeException("test exception");
	}

	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
System.out.println("MyWorker");
		MessageProperties messageProperties = message.getMessageProperties();
		String messageContent = (String) new SimpleMessageConverter().fromMessage(message);
		System.out.println("r[" + message + "]");
		
		// 写在前面会怎样?
		// channel.basicAck(messageProperties.getDeliveryTag(), true);
		
		
		doWord(messageContent);
System.out.println("deliveryTag是递增的");
System.out.println(messageProperties.getDeliveryTag());

		// 写在后面会怎样?
		// channel.basicAck(messageProperties.getDeliveryTag(), false);

		System.out.println("r[done]");
	}

}
 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. }  
package stephansun.github.samples.amqp.spring.workqueues;

import java.io.IOException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter;
import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class NewTask {
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
	
	private final static String QUEUE_NAME = "task_queue";
	
	public static void main(String[] args) throws IOException {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/workqueues/spring-rabbitmq-sender.xml");
		
		RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		String[] strs = new String[] { "First message." };

		String messageStr = getMessage(strs);
		
		MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter();
		MessageProperties messageProperties = 
				messagePropertiesConverter.toMessageProperties(
						com.rabbitmq.client.MessageProperties.PERSISTENT_TEXT_PLAIN, null, null);
		
		MessageConverter messageConverter = new SimpleMessageConverter();
		Message message = messageConverter.toMessage(messageStr, messageProperties);
		rabbitTemplate.send("", QUEUE_NAME, message);
		
		System.out.println("s[" + message + "]");
		
	}
}
 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. }  
package stephansun.github.samples.amqp.spring.workqueues;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Worker {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/workqueues/spring-rabbitmq-receiver.xml");
	}
}
 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template 
		id="rabbitTemplate" 
		connection-factory="connectionFactory"
		channel-transacted="true"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<rabbit:queue name="task_queue"
		durable="true"
		exclusive="false"
		auto-delete="false"/>
		
	<bean id="myWorker"
		class="stephansun.github.samples.amqp.spring.workqueues.MyWorker"/>
		
	<rabbit:listener-container 
		connection-factory="connectionFactory" 
		acknowledge="none"
		prefetch="1">
		<rabbit:listener ref="myWorker" queue-names="task_queue"/>
	</rabbit:listener-container>
	
		
</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<rabbit:queue name="task_queue"
		durable="true"
		exclusive="false"
		auto-delete="false"/>
		
</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. }  
package stephansun.github.samples.amqp.spring.publishsubscribe;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmitLog {
	
	private static final String EXCHANGE_NAME = "logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/publishsubscribe/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		String message = getMessage(new String[] { "test" });
		rabbitTempalte.send(EXCHANGE_NAME, "", messageConverter.toMessage(message, null));
		System.out.println("sent [" + message + "]");
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}
 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. }  
package stephansun.github.samples.amqp.spring.publishsubscribe;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ReceiveLogs {
	
	private static final String EXCHANGE_NAME = "logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/publishsubscribe/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");

		RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);

		FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME);
		rabbitAdmin.declareExchange(fanoutExchange);
		String queueName = rabbitAdmin.declareQueue().getName();
		Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, "", null);
		rabbitAdmin.declareBinding(binding);
		
		System.out.println("CTRL+C");
		
		// FIXME 为什么要在这里暂停10秒钟?
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Message message = rabbitTempalte.receive(queueName);
		Object obj = messageConverter.fromMessage(message);
		
		System.out.println("received:[" + obj + "]");
		
	}	
}
 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
</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. }  
package stephansun.github.samples.amqp.spring.routing;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmitLogDirect {

	private static final String EXCHANGE_NAME = "direct_logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/routing/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		// diff
		String serverity = getServerity(new String[] { "test" });
		String message = getMessage(new String[] { "test" });
		
		rabbitTempalte.send(EXCHANGE_NAME, serverity, messageConverter.toMessage(message, null));
		System.out.println("s[" + serverity + "]:[" + message + "]");
	}

	private static String getServerity(String[] strings) {
		return "info";
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}
 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. }  
package stephansun.github.samples.amqp.spring.routing;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ReceiveLogsDirect {

	private static final String EXCHANGE_NAME = "direct_logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/routing/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");

		RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);

		DirectExchange directExchange = new DirectExchange(EXCHANGE_NAME);
		rabbitAdmin.declareExchange(directExchange);
		String queueName = rabbitAdmin.declareQueue().getName();
		String[] strs = new String[] { "info", "waring", "error" };
		for (String str : strs) {
			Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, str, null);
			rabbitAdmin.declareBinding(binding);
		}
		
		System.out.println("CTRL+C");
		
		// FIXME 请你先思考一下,为什么要在这里暂停10秒钟?然后问我。
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Message message = rabbitTempalte.receive(queueName);
		Object obj = messageConverter.fromMessage(message);
		
		System.out.println("received:[" + obj + "]");
	}
}
 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
</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. }  
package stephansun.github.samples.amqp.spring.topics;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmitLogTopic {

	private static final String EXCHANGE_NAME = "topic_logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/topics/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		// diff
		String serverity = getServerity(new String[] { "test" });
		String message = getMessage(new String[] { "test" });
		
		rabbitTempalte.send(EXCHANGE_NAME, serverity, messageConverter.toMessage(message, null));
		System.out.println("s[" + serverity + "]:[" + message + "]");
	}

	private static String getServerity(String[] strings) {
		return "kern.critical";
	}
	
	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
	
}
 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. }  
package stephansun.github.samples.amqp.spring.topics;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ReceiveLogsTopic {
	

	private static final String EXCHANGE_NAME = "topic_logs";
	
	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/topics/spring-rabbitmq.xml");
		
		RabbitTemplate rabbitTempalte = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");

		RabbitAdmin rabbitAdmin = (RabbitAdmin) applicationContext.getBean(RabbitAdmin.class);

		TopicExchange directExchange = new TopicExchange(EXCHANGE_NAME);
		rabbitAdmin.declareExchange(directExchange);
		String queueName = rabbitAdmin.declareQueue().getName();
		String[] strs1 = new String[] { "#" };
		String[] strs2 = new String[] { "kern.*" };
		String[] strs3 = new String[] { "*.critical" };
		String[] strs4 = new String[] { "kern.*", "*.critical" };
		String[] strs5 = new String[] { "kern.critical", "A critical kernel error" };
		for (String str : strs5) {
			Binding binding = new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, str, null);
			rabbitAdmin.declareBinding(binding);
		}
		
		System.out.println("CTRL+C");
		
		// FIXME 为什么要在这里暂停10秒钟?
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Message message = rabbitTempalte.receive(queueName);
		Object obj = messageConverter.fromMessage(message);
		
		System.out.println("received:[" + obj + "]");
	}
	
}
 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
</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. }  
package stephansun.github.samples.amqp.spring.rpc;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RPCClient {
	
	private static String requestQueueName = "rpc_queue";
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/rpc/spring-rabbitmq-client.xml");
		
		RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
		
		String message = "30";
		Message reply = rabbitTemplate.sendAndReceive("", requestQueueName, new SimpleMessageConverter().toMessage(message, null));
		
		if (reply == null) {
			System.out.println("接收超时,返回null");
		} else {
			System.out.println("接收到消息:");
			System.out.println(reply);
		}
	}
}
 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. }  
package stephansun.github.samples.amqp.spring.rpc;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RPCServer {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/amqp/spring/rpc/spring-rabbitmq-server.xml");
	}
}
 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. }  
package stephansun.github.samples.amqp.spring.rpc;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

public class RPCServerListener implements MessageListener {

	private RabbitTemplate rabbitTemplate;

	private static MessageConverter messageConverter = new SimpleMessageConverter();
	
	public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	@Override
	public void onMessage(Message requestMessage) {
		Object obj = messageConverter.fromMessage(requestMessage);
		String str = (String) obj;
		int n = Integer.parseInt(str);
		System.out.println(" [.] fib(" + requestMessage + ")");
		String response = "" + fib(n);
		String replyTo = requestMessage.getMessageProperties().getReplyTo();
		rabbitTemplate.send(
				"", 
				replyTo, 
				messageConverter.toMessage(response, null));
	}

	private static int fib(int n) {
		if (n == 0) {
			return 0;
		}
		if (n == 1) {
			return 1;
		}
		return fib(n - 1) + fib(n - 2);
	}

}
 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory" reply-timeout="1000"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>

</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>

	<rabbit:queue name="rpc_queue"
		durable="false"
		exclusive="false"
		auto-delete="false">
	</rabbit:queue>
	
	<bean id="myListener"
		class="stephansun.github.samples.amqp.spring.rpc.RPCServerListener">
		<property name="rabbitTemplate" ref="rabbitTemplate"/>	
	</bean>
	
	<rabbit:listener-container connection-factory="connectionFactory" prefetch="1">
		<rabbit:listener queue-names="rpc_queue" ref="myListener"/>
	</rabbit:listener-container>
	
</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. }  
package stephansun.github.samples.amqp.spring.remoting;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(new String[] {
                		"stephansun/github/samples/amqp/spring/remoting/amqp-remoting.xml",
                		"stephansun/github/samples/amqp/spring/remoting/amqp-remoting-sender.xml",
                		"stephansun/github/samples/amqp/spring/remoting/amqp-remoting-receiver.xml"
                });
		MyService sender = (MyService) applicationContext.getBean("sender");
		sender.sayHello();
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("name", "stephan");
		param.put("age", 26);
		String str = sender.foo(param);
		System.out.println("str:" + str);
	}
}

 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. }  
package stephansun.github.samples.amqp.spring.remoting;

import java.util.Map;

public interface MyService {

	void sayHello();
	
	String foo(Map<String, Object> param);
	
}

 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. }  
package stephansun.github.samples.amqp.spring.remoting;

import java.util.Map;

public class MyServiceImpl implements MyService {

	@Override
	public void sayHello() {
		System.out.println("hello world!");
	}

	@Override
	public String foo(Map<String, Object> param) {
		return param.toString();
	}

}

 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="myService"
		class="stephansun.github.samples.amqp.spring.remoting.MyServiceImpl"/>
	
	<bean id="receiver"
		class="org.springframework.amqp.remoting.AmqpInvokerServiceExporter">
		<property name="serviceInterface" value="stephansun.github.samples.amqp.spring.remoting.MyService"/>
		<property name="service" ref="myService"/>
	</bean>
	
	<rabbit:listener-container 
		connection-factory="connectionFactory">
		<rabbit:listener ref="receiver" queue-names="si.test.queue"/>
	</rabbit:listener-container>
		
</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="sender"
		class="org.springframework.amqp.remoting.AmqpInvokerProxyFactoryBean">
		<property name="amqpTemplate" ref="amqpTemplate"/>
		<property name="serviceInterface" value="stephansun.github.samples.amqp.spring.remoting.MyService"/>
		<property name="exchange" value="si.test.exchange"/>
		<property name="routingKey" value="si.test.binding"/>
	</bean>
		
</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/rabbit 
		http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	
	<!-- Infrastructure -->
	
	<rabbit:connection-factory id="connectionFactory"/>
	
	<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>
	
	<rabbit:admin connection-factory="connectionFactory"/>
	
	<rabbit:queue name="si.test.queue"/>
	
	<rabbit:direct-exchange name="si.test.exchange">
		<rabbit:bindings>
			<rabbit:binding queue="si.test.queue" key="si.test.binding"/>
		</rabbit:bindings>
	</rabbit:direct-exchange>
		
</beans>

 关键的几个类有:

Java代码 复制代码  收藏代码
  1. org.springframework.amqp.remoting.AmqpInvokerClientIntecrptor   
  2. org.springframework.amqp.remoting.AmqpInvokerProxyFactoryBean   
  3. org.springframework.amqp.remoting.AmqpInvokerServiceExporter  
org.springframework.amqp.remoting.AmqpInvokerClientIntecrptor
org.springframework.amqp.remoting.AmqpInvokerProxyFactoryBean
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>  
<dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>3.1.0.RELEASE</version>
  	</dependency>
  </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. }   
package stephansun.github.samples.spring.remoting;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(new String[] {
                		"stephansun/github/samples/spring/remoting/spring-remoting.xml"
                });
		
		MyService myService = (MyService) applicationContext.getBean("sender");
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("name", "stephan");
		param.put("age", 26);
		String str = myService.foo(param);
		System.out.println("str:" + str);
	}
} 

  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. }  
package stephansun.github.samples.spring.remoting;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.remoting.support.DefaultRemoteInvocationFactory;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationFactory;
import org.springframework.remoting.support.RemoteInvocationResult;

public class MyInvokerClientInterceptor implements MethodInterceptor, InitializingBean {
	
	private RemoteInvocationFactory remoteInvocationFactory = new DefaultRemoteInvocationFactory();
	
	public void setRemoteInvocationFactory(RemoteInvocationFactory remoteInvocationFactory) {
		this.remoteInvocationFactory =
				(remoteInvocationFactory != null ? remoteInvocationFactory : new DefaultRemoteInvocationFactory());
	}
	
	protected RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
		return this.remoteInvocationFactory.createRemoteInvocation(methodInvocation);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet");
	}

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		RemoteInvocation invocation = createRemoteInvocation(methodInvocation);
		Object[] arguments = invocation.getArguments();
		System.out.println("arguments:" + arguments);
		String methodName = invocation.getMethodName();
		System.out.println("methodName:" + methodName);
		Class[] classes = invocation.getParameterTypes();
		System.out.println("classes:" + classes);
		// do whatever you want to do
		RemoteInvocationResult result = new RemoteInvocationResult("hello, world!");
		return result.getValue();
	}

}

 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. }  
package stephansun.github.samples.spring.remoting;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.ClassUtils;

public class MyInvokerProxyFactoryBean extends MyInvokerClientInterceptor
	implements FactoryBean<Object>, BeanClassLoaderAware {
	
	private Class serviceInterface;

	private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

	private Object serviceProxy;

	// FIXME for Spring injection
	public void setServiceInterface(Class serviceInterface) {
		this.serviceInterface = serviceInterface;
	}

	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		if (this.serviceInterface == null) {
			throw new IllegalArgumentException("Property 'serviceInterface' is required");
		}
		this.serviceProxy = new ProxyFactory(this.serviceInterface, this).getProxy(this.beanClassLoader);
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.beanClassLoader = classLoader;
	}

	@Override
	public Object getObject() throws Exception {
		return this.serviceProxy;
	}

	@Override
	public Class<?> getObjectType() {
		return this.serviceInterface;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}

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. }  
package stephansun.github.samples.spring.remoting;

import java.util.Map;

public interface MyService {

	void sayHello();
	
	String foo(Map<String, Object> param);
	
}

 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="sender"
		class="stephansun.github.samples.spring.remoting.MyInvokerProxyFactoryBean">
		<property name="serviceInterface" value="stephansun.github.samples.spring.remoting.MyService"/>
	</bean>
		
</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>  
<dependencies>
  	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-all</artifactId>
		<version>5.3.0</version>
  	</dependency>
  </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. }  
package stephansun.github.samples.jms.plain.pointtopoint;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

public class Receiver {

	public static void main(String[] args) {
		// 获得连接工厂
		ConnectionFactory cf = new ActiveMQConnectionFactory(
				"tcp://localhost:61616");
		
		// javax.jms.Connection
		Connection conn = null;
		// javax.jms.Session
		Session session = null;
		
		try {
			// 创建连接
			conn = cf.createConnection();
			
			// 创建会话
			session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			// 选择目标
			Destination destination = new ActiveMQQueue("myQueue");
			
			// 
			MessageConsumer consumer = session.createConsumer(destination);
			
			conn.start();
			
			// 接收消息
			Message message = consumer.receive();
			
			TextMessage textMessage = (TextMessage) message;
			System.out.println("得到一个消息:" + textMessage.getText());
		} catch (JMSException e) {
			// 处理异常
			e.printStackTrace();
		} finally {
			try {
				// 清理资源
				if (session != null) {
					session.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (JMSException ex) {
				ex.printStackTrace();
			}
		}
	}
	
}

 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. }  
package stephansun.github.samples.jms.plain.pointtopoint;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

public class Sender {

	public static void main(String[] args) {
		// 获得连接工厂
		ConnectionFactory cf = new ActiveMQConnectionFactory(
				"tcp://localhost:61616");
		
		// javax.jms.Connection
		Connection conn = null;
		// javax.jms.Session
		Session session = null;
		
		try {
			// 创建连接
			conn = cf.createConnection();
			
			// 创建会话
			session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			// 创建队列
			Destination destination = new ActiveMQQueue("myQueue");
			
			// 设置消息
			MessageProducer producer = session.createProducer(destination);
			TextMessage message = session.createTextMessage();
			message.setText("Hello World!");
			
			producer.send(message);
		} catch (JMSException e) {
			// 处理异常
			e.printStackTrace();
		} finally {
			try {
				// 清理资源
				if (session != null) {
					session.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (JMSException ex) {
				ex.printStackTrace();
			}
		}
	}
	
}

 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. }  
package stephansun.github.samples.jms.plain.pubsub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;

public class Receiver1 {

	public static void main(String[] args) {
		// 获得连接工厂
		ConnectionFactory cf = new ActiveMQConnectionFactory(
				"tcp://localhost:61616");
		
		// javax.jms.Connection
		Connection conn = null;
		// javax.jms.Session
		Session session = null;
		
		try {
			// 创建连接
			conn = cf.createConnection();
			
			// 创建会话
			session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			// 选择目标
			Destination destination = new ActiveMQTopic("myTopic");
			
			// 
			MessageConsumer consumer = session.createConsumer(destination);
			
			conn.start();
			
			// 接收消息
			Message message = consumer.receive();
			
			TextMessage textMessage = (TextMessage) message;
			System.out.println("接收者1 得到一个消息:" + textMessage.getText());
		} catch (JMSException e) {
			// 处理异常
			e.printStackTrace();
		} finally {
			try {
				// 清理资源
				if (session != null) {
					session.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (JMSException ex) {
				ex.printStackTrace();
			}
		}
	}
	
}

 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. }  
package stephansun.github.samples.jms.plain.pubsub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;

public class Sender {

	public static void main(String[] args) {
		// 获得连接工厂
		ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
		
		// javax.jms.Connection
		Connection conn = null;
		// javax.jms.Session
		Session session = null;
		
		try {
			// 创建连接
			conn = cf.createConnection();
			
			// 创建会话
			session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			
			// 创建队列
			Destination destination = new ActiveMQTopic("myTopic");
			
			// 设置消息
			MessageProducer producer = session.createProducer(destination);
			TextMessage message = session.createTextMessage();
			message.setText("Hello World!");
			
			producer.send(message);
		} catch (JMSException e) {
			// 处理异常
			e.printStackTrace();
		} finally {
			try {
				// 清理资源
				if (session != null) {
					session.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (JMSException ex) {
				ex.printStackTrace();
			}
		}
	}
	
}

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>  
<dependencies>
  	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-all</artifactId>
		<version>5.3.0</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jms</artifactId>
  		<version>3.1.0.RELEASE</version>
  	</dependency>
  </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. }   
package stephansun.github.samples.jms.spring.pointtopoint;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;

public class Receiver {

	public static void main(String[] args) throws JMSException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/jms/spring/pointtopoint/jms-point-to-point.xml");
        
        Queue myQueue = (Queue) applicationContext.getBean("myQueue");
        JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
        
        MapMessage message = (MapMessage) jmsTemplate.receive(myQueue);
        
        String name = message.getString("name");
        int age = message.getInt("age");
        
        System.out.println("name:" + name);
        System.out.println("age:" + age);
    }
	
} 

  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. }  
package stephansun.github.samples.jms.spring.pointtopoint;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class Sender {

	public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/jms/spring/pointtopoint/jms-point-to-point.xml");
        
        Queue myQueue = (Queue) applicationContext.getBean("myQueue");
        JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
        
        jmsTemplate.send(myQueue, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				message.setString("name", "stephan");
				message.setInt("age", 26);
				return message;
			}
        });
    }
	
}

 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="connectionFactory"
		class="org.apache.activemq.ActiveMQConnectionFactory"/>
		
	<bean id="myQueue"
		class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg index="0" value="myQueue"/>	
	</bean>
		
	<bean id="jmsTemplate"
		class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory" ref="connectionFactory"/>	
	</bean>
		
</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. }  
package stephansun.github.samples.jms.spring.pubsub;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Topic;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;

public class Receiver1 {

	public static void main(String[] args) throws JMSException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/jms/spring/pubsub/jms-pub-sub.xml");
        
        Topic myTopic = (Topic) applicationContext.getBean("myTopic");
        JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
        
        MapMessage message = (MapMessage) jmsTemplate.receive(myTopic);
        
        String name = message.getString("name");
        int age = message.getInt("age");
        
        System.out.println("name:" + name);
        System.out.println("age:" + age);
    }
	
}

 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. }  
package stephansun.github.samples.jms.spring.pubsub;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.Topic;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class Sender {

	public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(
                		"stephansun/github/samples/jms/spring/pubsub/jms-pub-sub.xml");
        
        Topic myTopic = (Topic) applicationContext.getBean("myTopic");
        JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
        
        jmsTemplate.send(myTopic, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				message.setString("name", "stephan");
				message.setInt("age", 26);
				return message;
			}
        });
    }
	
}

 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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="connectionFactory"
		class="org.apache.activemq.ActiveMQConnectionFactory"/>
		
	<bean id="myTopic"
		class="org.apache.activemq.command.ActiveMQTopic">
		<constructor-arg index="0" value="myTopic"/>	
	</bean>
		
	<bean id="jmsTemplate"
		class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory" ref="connectionFactory"/>	
	</bean>
		
</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>  
<dependencies>
  	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-all</artifactId>
		<version>5.3.0</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jms</artifactId>
  		<version>3.1.0.RELEASE</version>
  	</dependency>
  </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. }  
package stephansun.github.samples.jms.spring.remoting;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext(new String[] {
                		"stephansun/github/samples/jms/spring/remoting/jms-remoting.xml",
                		"stephansun/github/samples/jms/spring/remoting/jms-remoting-sender.xml",
                		"stephansun/github/samples/jms/spring/remoting/jms-remoting-receiver.xml"
                });
		MyService sender = (MyService) applicationContext.getBean("sender");
		sender.sayHello();
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("name", "stephan");
		param.put("age", 26);
		String str = sender.foo(param);
		System.out.println("str:" + str);
	}
}

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. }   
package stephansun.github.samples.jms.spring.remoting;

import java.util.Map;

public interface MyService {

	void sayHello();
	
	String foo(Map<String, Object> param);
	
} 

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. }   
package stephansun.github.samples.jms.spring.remoting;

import java.util.Map;

public class MyServiceImpl implements MyService {

	@Override
	public void sayHello() {
		System.out.println("hello world!");
	}

	@Override
	public String foo(Map<String, Object> param) {
		return param.toString();
	}

} 

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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="myService"
		class="stephansun.github.samples.jms.spring.remoting.MyServiceImpl"/>
	
	<bean id="receiver"
		class="org.springframework.jms.remoting.JmsInvokerServiceExporter">
		<property name="serviceInterface" value="stephansun.github.samples.jms.spring.remoting.MyService"/>
		<property name="service" ref="myService"/>
	</bean>
	
	<bean id="container"
		class="org.springframework.jms.listener.DefaultMessageListenerContainer">
		<property name="connectionFactory" ref="connectionFactory"/>
		<property name="messageListener" ref="receiver"/>
		<property name="destination" ref="myQueue"/>	
	</bean>
		
</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="sender"
		class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean">
		<property name="connectionFactory" ref="connectionFactory"/>
		<property name="queue" ref="myQueue"/>
		<property name="serviceInterface" value="stephansun.github.samples.jms.spring.remoting.MyService"/>
		<property name="receiveTimeout" value="5000"/>
	</bean>
		
</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>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="connectionFactory"
		class="org.apache.activemq.ActiveMQConnectionFactory"/>
		
	<bean id="myQueue"
		class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg index="0" value="myQueue"/>	
	</bean>
		
	<bean id="jmsTemplate"
		class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory" ref="connectionFactory"/>	
	</bean>
		
</beans>

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

猜你喜欢

转载自zxb1985.iteye.com/blog/1813841