rabbitmq实操一
程序员文章站
2022-04-10 23:25:31
...
1.maven工程
2.编写一个连接工具类
public class ConnectionUtil {
public static Connection getConnection() throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址,默认为localhost
factory.setHost("106.15.196.212");
//连接端口(并不是web管理后台的15672)
factory.setPort(5672);
//设置虚拟主机
factory.setVirtualHost("/mytest");
//连接用户名,默认为guest
factory.setUsername("dkx");
//密码,默认为guest
factory.setPassword("123456");
//创建连接
Connection connection = factory.newConnection();
return connection;
}
}
3.创建生产者
public class Producer {
static final String QUEUE_NAME = "simple_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = null;
Channel channel = null;
try {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址,默认为localhost
factory.setHost("106.15.196.212");
//连接端口(并不是web管理后台的15672)
factory.setPort(5672);
//设置虚拟主机
factory.setVirtualHost("/mytest");
//连接用户名,默认为guest
factory.setUsername("dkx");
//密码,默认为guest
factory.setPassword("123456");
//创建连接
connection = factory.newConnection();
//创建频道
channel = connection.createChannel();
//声明创建队列
/**
* 参数一:队列名称
* 参数二:是否定义持久化队列
* 参数三:是否独占本次连接
* 参数四:是否在不使用的时候自动删除队列
* 参数五:队列其他参数
*/
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
//要发送的消息
String msg = "我的rabbitmq测试!!";
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
System.out.println("======已发送消息==========>"+msg);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
//释放资源
channel.close();
connection.close();
}
}
}
4.创建消费者
public class Consumer {
public static void main(String[] args) throws IOException, TimeoutException {
//获取连接
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//创建队列:消费者,并设置消费处理
channel.queueDeclare(Producer.QUEUE_NAME,true,false,false,null);
//监听消息
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("路由key为:"+envelope.getRoutingKey());
System.out.println("交换机为:"+envelope.getExchange());
System.out.println("消息id为:"+envelope.getDeliveryTag());
System.out.println("接收到的消息:"+new String(body,"Utf-8"));
System.out.println("==============================");
}
};
/**
* 监听消息
* 参数一:队列名称
* 参数二:是否自动确认(true表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认)
*
*/
channel.basicConsume(Producer.QUEUE_NAME,true,consumer);
//不关闭资源,应该保持监听
/*channel.close();
connection.close();*/
}
}
测试