例子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. [javascript-snippet]使用javascript+html5实现图片的灰度处理

    // 源码出自:潇湘夜雨<!DOCTYPE> <html> <head> <meta charset="utf-8"/> </ ...

  2. cudnn 安装步骤

    上官网下载对应的cudnn https://developer.nvidia.com/cudnn 下载完cudnn后,命令行输入文件所在的文件夹 (ubuntu为本机用户名) cd home/ubun ...

  3. PCA和Whitening

    PCA: PCA的具有2个功能,一是维数约简(可以加快算法的训练速度,减小内存消耗等),一是数据的可视化. PCA并不是线性回归,因为线性回归是保证得到的函数是y值方面误差最小,而PCA是保证得到的函 ...

  4. windows 7 下elasticsearch5.0 安装head 插件

    windows 7 下elasticsearch5.0 安装head 插件 elasticsearch5.0 和2有了很大的变化,以前的很多插件都有了变化比如 bigdesk head,以下是安装he ...

  5. JS学习笔记6_事件

    1.事件冒泡 由内而外的事件传播(从屏幕里飞出来一支箭的感觉) 2.事件捕获 由表及里的事件传播(力透纸背的感觉) 3.DOM事件流(DOM2级) 事件捕获阶段 -> 处于目标阶段 -> ...

  6. Node.js之绝对选择(2018版)

    [这篇是很早期的文字,由于引用较广泛,担心误导,故按照现在的情形做一些修改] 几年前,完全放弃Asp.net,彻底脱离微软方向.Web开发,在公司团队中,一概使用Node.js.Mongodb.Git ...

  7. 托管博客到coding或者github

    1. 部署网站到github的pages服务 参考: <在Github上面搭建Hexo博客(一):部署到Github> <Hexo搭建独立博客,托管到Github和Coding上教程 ...

  8. winform 查找控件并获取特定类型控件

    //通过反射获取所有控件集合 System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection. ...

  9. EF Core 迁移过程遇到EF Core tools version版本不相符的解决方案

    如果你使用命令: PM> add-migration Inital 提示如下信息时: The EF Core tools version '2.1.1-rtm-30846' is older t ...

  10. [Leetcode]120.三角形路径最小和

    ---恢复内容开始--- 题目的链接 简单的动态规划题,使用了二维dp数组就能很好的表示. 由于有边界的问题,所以这个dp数组为 dp[n+1][n+1]. dp[i][j]意思是终点为(i-1,j- ...