java 操作 RabbitMQ 发送、接受消息
例子1
Producer.java
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory; public class Producer {
public final static String QUEUE_NAME="rabbitMQ_test2"; public static void main(String[] args) throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory(); //设置RabbitMQ相关信息
factory.setHost("100.51.15.10");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setPort(5672); //创建一个新的连接
Connection connection = factory.newConnection(); //创建一个通道
Channel channel = connection.createChannel(); // 声明一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null); //发送消息到队列中
String message = "Hello RabbitMQ";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer Send +'" + message + "'"); //关闭通道和连接
channel.close();
connection.close();
}
}
Consumer.java
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP; public class Customer {
private final static String QUEUE_NAME = "rabbitMQ_test2"; public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接工厂
ConnectionFactory factory = new ConnectionFactory(); //设置RabbitMQ地址
factory.setHost("100.51.15.10");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setPort(5672); //创建一个新的连接
Connection connection = factory.newConnection(); //创建一个通道
Channel channel = connection.createChannel(); //声明要关注的队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Customer Waiting Received messages"); //DefaultConsumer类实现了Consumer接口,通过传入一个频道,
// 告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
Consumer consumer = new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("Customer Received '" + message + "'");
}
};
//自动回复队列应答 -- RabbitMQ中的消息确认机制
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
执行
Producer.java
Producer Send +'Hello RabbitMQ'
Producer Send +'Hello RabbitMQ'
Consumer.java
Customer Received 'Hello RabbitMQ'
Customer Received 'Hello RabbitMQ'
例子2
首先写一个类,将产生产者和消费者统一为 EndPoint类型的队列。不管是生产者还是消费者,连接队列的代码都是一样的,这样可以通用一些。
EndPoint.java
//package co.syntx.examples.rabbitmq; import java.io.IOException;
import java.util.concurrent.TimeoutException; import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory; /**
* Represents a connection with a queue
* @author syntx
*
*/
public abstract class EndPoint{ protected Channel channel;
protected Connection connection;
protected String endPointName; public EndPoint(String endpointName) throws IOException{
this.endPointName = endpointName; //Create a connection factory
ConnectionFactory factory = new ConnectionFactory(); //hostname of your rabbitmq server
factory.setHost("100.51.15.10");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setPort(5672); //getting a connection
try{
connection = factory.newConnection();
}catch (TimeoutException ex) {
System.out.println(ex);
connection = null;
} //creating a channel
channel = connection.createChannel(); //declaring a queue for this channel. If queue does not exist,
//it will be created on the server.
channel.queueDeclare(endpointName, false, false, false, null);
} /**
* 关闭channel和connection。并非必须,因为隐含是自动调用的。
* @throws IOException
*/
public void close() throws IOException{
try{
this.channel.close();
} catch (TimeoutException ex){
System.out.println("ex" + ex);
}
this.connection.close();
}
}
Producer2.java
import java.io.IOException;
import java.io.Serializable; import org.apache.commons.lang.SerializationUtils; public class Producer2 extends EndPoint{ public Producer2(String endPointName) throws IOException{
super(endPointName);
} public void sendMessage(Serializable object) throws IOException {
channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object));
}
}
QueueConsumer.java
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.lang.SerializationUtils; import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException; public class QueueConsumer extends EndPoint implements Runnable, Consumer{ public QueueConsumer(String endPointName) throws IOException{
super(endPointName);
} public void run() {
try {
//start consuming messages. Auto acknowledge messages.
channel.basicConsume(endPointName, true,this);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* Called when consumer is registered.
*/
public void handleConsumeOk(String consumerTag) {
System.out.println("Consumer "+consumerTag +" registered");
} /**
* Called when new message is available.
*/
public void handleDelivery(String consumerTag, Envelope env,
BasicProperties props, byte[] body) throws IOException {
Map map = (HashMap)SerializationUtils.deserialize(body);
System.out.println("Message Number "+ map.get("message number") + " received."); } public void handleCancel(String consumerTag) {}
public void handleCancelOk(String consumerTag) {}
public void handleRecoverOk(String consumerTag) {}
public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}
}
Main.java
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap; public class Main {
public Main() throws Exception{ QueueConsumer consumer = new QueueConsumer("queue");
Thread consumerThread = new Thread(consumer);
consumerThread.start(); Producer2 producer = new Producer2("queue"); for (int i = 0; i < 5; i++) {
HashMap message = new HashMap();
message.put("message number", i);
producer.sendMessage(message);
System.out.println("Message Number "+ i +" sent.");
}
} public static void main(String[] args) throws Exception{
new Main();
System.out.println("##############end...");
}
}
java 操作 RabbitMQ 发送、接受消息的更多相关文章
- java操作RabbitMQ添加队列、消费队列和三个交换机
假设已经在服务器上安装完RabbitMQ.我写的教程 一.发送消息到队列(生产者) 新建一个maven项目,在pom.xml文件加入以下依赖 <dependencies> <depe ...
- EasyNetQ操作RabbitMQ(高级消息队列)
RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件).写消息队列的时候用RabbitMQ比较好,但是写的时候需要自己封装下,自己的封装,就需要对RabbitM ...
- java操作rabbitmq实现简单的消息发送(socket编程的升级)
准备: 1.下载rabbitmq并搭建环境(和python那篇一样:http://www.cnblogs.com/g177w/p/8176797.html) 2.下载支持的jar包(http://re ...
- 1.java soap api操作和发送soap消息
转自:https://blog.csdn.net/lbinzhang/article/details/84721359 1. /** * soap请求 * * @return * @throws Ex ...
- java微信开发之接受消息回复图片或者文本
上回说到 接口连接成功,接下来是真正的开发了. 消息的接收,整个过程就是关注订阅号的用户在微信订阅号中发送消息,微信服务器接收到消息,将消息发给开发者的服务器,服务器接收消息然后可以根据内容进行回复. ...
- 【Spring】使用Spring和AMQP发送接收消息(上)
讲AMQP之前,先讲下传统的JMS的消息模型,JMS中主要有三个参与者:消息的生产者.消费者.传递消息的通道(队列或者主题),两种消息模型如下:通道是队列: 通道是队列: 通道是主题: 在JMS中,虽 ...
- 【转载】java实现rabbitmq消息的发送接受
原文地址:http://blog.csdn.net/sdyy321/article/details/9241445 本文不介绍amqp和rabbitmq相关知识,请自行网上查阅 本文是基于spring ...
- 【Azure 事件中心】在微软云中国区 (Mooncake) 上实验以Apache Kafka协议方式发送/接受Event Hubs消息 (Java版)
问题描述 事件中心提供 Kafka 终结点,现有的基于 Kafka 的应用程序可将该终结点用作运行你自己的 Kafka 群集的替代方案. 事件中心可与许多现有 Kafka 应用程序配合使用.在Azur ...
- java框架之SpringBoot(12)-消息及整合RabbitMQ
前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...
随机推荐
- hdu 5083 有坑+字符串模拟水题
http://acm.hdu.edu.cn/showproblem.php?pid=5083 机器码和操作互相转化 注意SET还要判断末5位不为0输出Error #pragma comment(lin ...
- 冲刺博客NO.2
今日做了什么: 了解到Mob.com有全球短信验证功能,按照官方集成文档下载了SDK,但是还不会写(正在慕课网上学习). 掌握了android开发的一些流程,熟悉了android studio的语 ...
- Idea14 生成webservices
一直为idea生成soap协议的webservices而纠结,当初做axis2的时候,用的是eclipse,用它的插件来生成.这次做短信平台,决定要换一下,因为eclipse用axis2生成的接口,会 ...
- pycharm光标变成黑框,恢复成竖线
pycharm光标变成黑框,如下图所示 解决办法: 按外接键盘上的Insert键,即可恢复.
- BZOJ 3357--[Usaco2004]等差数列(STL&DP)
3357: [Usaco2004]等差数列 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 516 Solved: 241[Submit][Statu ...
- ReactNatvie遇到的错误
1:新版的React包中没有包含PropTypes,如果使用需要从‘prop-types’包中导入. 2: 'prop-types'包中直接定义‘PropTypes.style’是无效的,需要使用‘P ...
- 阿里云mysql数据库备份还原
1.下载备份包 在rds的备份恢复中点击下载,在弹出的窗口中复制内网下载地址(前提是目标服务器与rds内网互通,否则请复制外网地址) 在目标服务器中执行如下命令进行下载: wget -c '复制的地址 ...
- Linux上安装java JDK
yum方式 1.查看yum中的各个版本 yum -y list java* 2.选择一个版本安装(如1.7) yum -y install java-1.7.0-openjdk* 3.安装完成后可查看 ...
- com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
出现上述bug的原因如下: 在默认设置下,Eureka服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为. 禁止方式如下:在application.propertie ...
- Data - 数据思维
数据思维 数据思维全解析 如何建立数据分析的思维框架 做数据分析时,你的方法论是什么? 数据分析全流程资料,适合各路人马 百度内部培训资料PPT:数据分析的道与术 学会数据分析背后的挖掘思维,分析就完 ...