生产者:
public class Producer01 {
private final static String QUENE="hello_word";
public static void main(String[] args) {
//通过连接工厂创建新的连接和mq建立连接
ConnectionFactory connectionFactory=new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
//设置虚拟机,每个虚拟机就相当于一个独立的mq
connectionFactory.setVirtualHost("/");
//建立新连接
Connection connection=null;
Channel channel =null;
try {
connection=connectionFactory.newConnection();
channel=connection.createChannel();
//声明队列:如果队列在mq没有则要创建
/**
* 参数明细
* 1、队列名称
* 2、是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,也就是换一个连接就不能访问了,如果连接关闭后连接就自动删除了
* 如果将此参数设置true可用于临时队列的创建
* 4、自动删除 队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(QUENE,true,false,false,null);
//发送消息
/**
* 参数明细
* 1、exchange,交换机,如果不指定将使用mq的默认交换机
* 2、routingKey,路由key,交换机根据路由key来将消息转发到指定的队列名称
* 3、props,消息的属性
* 4、消息的内容
*/
//消息内容
String message="hellow world 接收到消息了吗";
channel.basicPublish("", QUENE,null,message.getBytes());
System.out.println("Send to mq message");
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
//关闭连接
//关闭通道
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
消费者:
public class Consumer {
private final static String QUENE="hello_word";
public static void main(String[] args)throws Exception {
//通过连接工厂创建新的连接和mq建立连接
ConnectionFactory connectionFactory=new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
//设置虚拟机,每个虚拟机就相当于一个独立的mq
connectionFactory.setVirtualHost("/");
Connection connection=null;
connection=connectionFactory.newConnection();
Channel channel=connection.createChannel();
//声明队列
channel.queueDeclare(QUENE,true,false,false,null);
//实现消费方法
DefaultConsumer defaultConsumer =new DefaultConsumer(channel){
//当接收到消息后 此方法将被调用
/**
*
* @param consumerTag 消费者标签,用来标识消费者的,在监听队列时设置channel.basicConsume
* @param envelope 信封,通过envlope
* @param properties
* @param body
* @throws IOException
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//交换机
String exchange= envelope.getExchange();
//消息id, mq在channel 中用来标识消息的id,可用于接收
long deliveryTag =envelope.getDeliveryTag();
//消息内容
String message=new String(body,"utf-8");
System.out.println("receive message:"+message);
}
};
//监听队列
//1、队列名称
//2、自动回复 ,当消费者收到消息后要告诉mq消息已接收,如果将此参数设置为true表示会自动回复mq,如果设置为false要通过编程实现回复
//3、callback,消费方法,当消费者接收到消息要执行的方法
channel.basicConsume(QUENE,true,defaultConsumer);
}
}