生产者代码块
package com.cloudtech.web.mq;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.cloudtech.web.util.RabbitmqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
* 生产者
* @ClassName: Sender
* @Description:
* @author wude
* @date 2018年7月31日
*
*/
public class Sender {
private final static String QUEUE="testhello";
public static void main(String[] args) {
//获取连接
try {
Connection connection = RabbitmqUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
//声明队列 说明队列存在则什么都不做 如果不存在则自动创建
//参数1.队列名称
//参数2 是否持久化队列,我们中的队列模式是指内存中的,如果rabbit重启会丢失,如果我们设置为true,则会保存到el-lang自带的数据库中重启后,会重新读取
//参数3 是否排外,有两个作用,当我们连接关闭后,是否自动关闭队列,作用二 是否私用当天的队列,如果私有了,则其他队列不允许访问,如果为true,一般只适用于一个消费者的时候
//参数4 是否自动删除
//参数5我们的一些其他参数
channel.queueDeclare(QUEUE,false,false,false,null);
//发送内容
channel.basicPublish("", QUEUE, null, "发送的消息".getBytes());
//关闭连接
channel.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
消费者代码
package com.cloudtech.web.mq;
import java.io.IOException;
import com.cloudtech.web.util.RabbitmqUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
/**
*
* @ClassName: Recver
* @Description: 消费者
* @author wude
* @date 2018年7月31日
*
*/
public class Recver {
private final static String QUEUE="testhello";
public static void main(String[] args) throws Exception{
Connection connection = RabbitmqUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE, false, false, false, null);
//接受消息
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
//获取消费者
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
//参数1 队列名称
//参数2 自动确认
channel.basicConsume(QUEUE, true, consumer);
}
}
工具类块:
package com.cloudtech.web.util;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitmqUtils {
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.1.198");
factory.setUsername("admin");
factory.setPassword("admin");
Connection connection = factory.newConnection();
return connection;
}
}