例子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 发送、接受消息的更多相关文章

  1. java操作RabbitMQ添加队列、消费队列和三个交换机

    假设已经在服务器上安装完RabbitMQ.我写的教程 一.发送消息到队列(生产者) 新建一个maven项目,在pom.xml文件加入以下依赖 <dependencies> <depe ...

  2. EasyNetQ操作RabbitMQ(高级消息队列)

    RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件).写消息队列的时候用RabbitMQ比较好,但是写的时候需要自己封装下,自己的封装,就需要对RabbitM ...

  3. java操作rabbitmq实现简单的消息发送(socket编程的升级)

    准备: 1.下载rabbitmq并搭建环境(和python那篇一样:http://www.cnblogs.com/g177w/p/8176797.html) 2.下载支持的jar包(http://re ...

  4. 1.java soap api操作和发送soap消息

    转自:https://blog.csdn.net/lbinzhang/article/details/84721359 1. /** * soap请求 * * @return * @throws Ex ...

  5. java微信开发之接受消息回复图片或者文本

    上回说到 接口连接成功,接下来是真正的开发了. 消息的接收,整个过程就是关注订阅号的用户在微信订阅号中发送消息,微信服务器接收到消息,将消息发给开发者的服务器,服务器接收消息然后可以根据内容进行回复. ...

  6. 【Spring】使用Spring和AMQP发送接收消息(上)

    讲AMQP之前,先讲下传统的JMS的消息模型,JMS中主要有三个参与者:消息的生产者.消费者.传递消息的通道(队列或者主题),两种消息模型如下:通道是队列: 通道是队列: 通道是主题: 在JMS中,虽 ...

  7. 【转载】java实现rabbitmq消息的发送接受

    原文地址:http://blog.csdn.net/sdyy321/article/details/9241445 本文不介绍amqp和rabbitmq相关知识,请自行网上查阅 本文是基于spring ...

  8. 【Azure 事件中心】在微软云中国区 (Mooncake) 上实验以Apache Kafka协议方式发送/接受Event Hubs消息 (Java版)

    问题描述 事件中心提供 Kafka 终结点,现有的基于 Kafka 的应用程序可将该终结点用作运行你自己的 Kafka 群集的替代方案. 事件中心可与许多现有 Kafka 应用程序配合使用.在Azur ...

  9. java框架之SpringBoot(12)-消息及整合RabbitMQ

    前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...

随机推荐

  1. iOS中的序列帧动画

    UIImageView对象的有一个animationImages属性,将图片数组赋值给该属性即可.如图: 控制动画的播放方法是:[ ___  startAnimating]; 控制动画的停止方法是:[ ...

  2. Hbase_shell操作

    创建表 create 'user_action_table', 'action_log', 'action'-- 执行结果=> Hbase::Table - m_table 描述表信息 desc ...

  3. Oracle EBS R12 XML数据表格的Excel脚本报表

    http://www.cnblogs.com/quanweiru/archive/2012/07/28/2612680.html 一.概述 在EBS系统中,报表是一个非常重要的客户化开发内容,也是系统 ...

  4. 把EXE可执行文件等作为资源包含在Delphi编译文件中

    摘自我自己过去写的一段心得. 1.编辑资源文件 *.RCWave: 资源文件是声音文件:RCDATA: 二进制数据AVI: AVI动画:ICON: 图标文件:BITMAP: 位图文件:CURSOR: ...

  5. 在推送提交之后阻止Azure DevOps (TFS)持续集成

    在Azure DevOps服务器上配置生成定义时,可以配置连续集成(CI)生成.每次签入或提交到源代码库时都会自动运行一个CI构建.这种机制允许开发人员启动一个自动化的过程,例如编译和部署构建.这是一 ...

  6. WPF 定义Lookless控件的默认样式、 OnApplyTemplate 如何使用(实现方式、如何工作的)!

    写的非常详细: 作者地址:https://www.cnblogs.com/atskyline/archive/2012/11/16/2773806.html 参考资料: http://www.code ...

  7. 定时任务 Wpf.Quartz.Demo.1

    Quartz 是个开源的作业调度框架. 安装:Install-Package Quartz 官网文档地址:https://www.quartz-scheduler.net/documentation/ ...

  8. Android--------------BroadcastReceiver的学习

    一.广播的注册方式 发送广播: Intent mIntent = new Intent("com.simware.BroadcastReceiverDemo"); mIntent. ...

  9. mysql多列索引

    1,数据库每次查询只能使用一个索引 2,假设数据 表T (a,b,c) rowid 为物理位置rowid a b c(1) 1 1 1(2) 2 1 13(3) 2 2 14(4) 1 3 3(5)  ...

  10. 使用sqlmap对进行php+mysql注入实战

    作者:陈小兵一般来讲一旦网站存在sql注入漏洞,通过sql注入漏洞轻者可以获取数据,严重的将获取webshell以及服务器权限,但在实际漏洞利用和测试过程中,也可能因为服务器配置等情况导致无法获取权限 ...