RabbitMQ Learning [1] “Hello World” 模式(Java 版)

“Hello World” 模式如下图,publisher(生产者)发送消息到MQ,consumer(消费者)监听MQ获得消息。

在这里插入图片描述

1. 生产者发送消息到队列(Sending)

在这里插入图片描述
首先可先创建一个RabbitMQ连接获取工具类,封装获取连接的方法

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUntil
{
    private final static String host = "localhost"; //RabbitMQ server 地址
    private final static int port = 5672; //端口
    private final static String user = "admin"; //用户名
    private final static String pwd = "admin"; // 密码
    private final static String vHost = "testhost"; //RabbitMQ中Erlang虚拟机名字,可使用默认的虚拟机
    public static Connection getConnection() throws Exception
    {
        //声明Connection工厂类
        final ConnectionFactory cFactory = new ConnectionFactory();
        //设置地址
        cFactory.setHost(host);
        //设置端口
        cFactory.setPort(port);
        //设置虚拟机,可不设置使用默认
        cFactory.setVirtualHost(vHost);
        //设置用户名
        cFactory.setUsername(user);
        //设置密码
        cFactory.setPassword(pwd);
        //获得连接
        final Connection connection = cFactory.newConnection();
        return connection;
    }
}

然后创建生产者类,并获得连接发送“Hello World”消息

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class Producer
{
    private final static String QUEUE_NAME = "test_1"; // 队列名
    public static void main(final String[] args) throws Exception
    {
    	try ( // 调用工具类创建连接
    	      final Connection connection = ConnectionUntil.getConnection();
    	      // 创建通道(通道包括生产通道和消费通道)
    	      final Channel channel = connection.createChannel();){

            // 声明通道的消息队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            // 创建待发送的消息
            final String message = "Hello World";
            // 发布消息到队列
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println("[x] Sent'" + message + "'");

    	}

    }

}


2. 消费者监听队列获得消息(Receiving)

在这里插入图片描述
不像生产者只需发送一个单个的消息,消费者需要不停的监听消息队列来保证可以获得消息

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
public class Consumer
{
    private final static String QUEUE_NAME = "test_1";// 队列名,与生产者的目标队列名一致

    public static void main(final String[] args) throws Exception
    {
        final Connection connection = ConnectionUntil.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //消息递送后的回调函数
        final DeliverCallback deliverCallback = (consumerTag,delivery)->{
            final String message = new String(delivery.getBody(),"UTF-8");
            System.out.println("[x] Received'" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag ->
        {
        });
    }
}

消费者中也声明了队列,这是因为我们可能在生产者运行之前运行消费者,我们需要保证在进行获得消息操作之前消息队列的存在。另外,这里没有用try-with-resource来自动地关闭channel和connection,这是因为当消费者异步监听将要到达的消息的过程中,进程需要一直运行。我们以对象的方式提供了一个回调函数,它可以缓存获得到的消息,以待我们需要的使用这些消息的时候。

3.运行

首先运行Consumer类保证消费者处于监听状态,然后运行生产者发送消息。运行结果如下:
生产者成功发送消息:
在这里插入图片描述
消费者成功接收消息:
在这里插入图片描述

参考文献:
[1] http://next.rabbitmq.com/tutorials/tutorial-one-java.html
[2] https://blog.csdn.net/hellozpc/article/details/81436980

代码可见:https://github.com/ShaneShen0/RabbitMQDemo

Key Features, Learn to administer, configure, and manage RabbitMQ instancesDiscover ways to secure and troubleshoot RabbitMQ instancesThis book is fully up-to-date with all the latest changes to version 3.5, Book Description, RabbitMQ is Open Source Message Queuing software based on the Advanced Message Queue Protocol Standard written in the Erlang Language. RabbitMQ is an ideal candidate for large-scale projects ranging from e-commerce and finance to Big Data and social networking because of its ease of use and high performance. Managing RabbitMQ in such a dynamic environment can be a challenging task that requires a good understanding not only of how to work properly with the message broker but also of its best practices and pitfalls., Learning RabbitMQ starts with a concise description of messaging solutions and patterns, then moves on to concrete practical scenarios for publishing and subscribing to the broker along with basic administration. This knowledge is further expanded by exploring how to establish clustering and high availability at the level of the message broker and how to integrate RabbitMQ with a number of technologies such as Spring, and enterprise service bus solutions such as MuleESB and WSO2. We will look at advanced topics such as performance tuning, secure messaging, and the internals of RabbitMQ. Finally we will work through case-studies so that we can see RabbitMQ in action and, if something goes wrong, we'll learn to resolve it in the Troubleshooting section., What you will learn, Apply messaging patterns using the message brokerAdminister RabbitMQ using the command line, management Web console, or management REST servicesCreate a cluster of scalable, and highly-available, RabbitMQ instancesUse RabbitMQ with the Spring Framework, MuleESB, WSO2, and Oracle databasesDeploy RabbitMQ using Puppet, Vagrant, or DockerFine-tune the performance of RabbitMQMonitor RabbitMQ using Nagios, Munin, or MonitSecure, troubleshoot, and extend RabbitMQ, About the Author, Martin Toshev is a software developer and Java enthusiast with more than eight years of experience and vast expertise originating from projects in areas such as enterprise Java, social networking, source code analysis, Internet of Things, and investment banking in companies such as Cisco and Deutsche Telekom. He is a graduate of computer science from the University of Sofia. He is also a certified Java professional (SCJP6) and a certified IBM cloud computing solution advisor. His areas of interest include a wide range of Java-related technologies (Servlets, JSP, JAXB, JAXP, JMS, JMX, JAX-RS, JAX-WS, Hibernate, Spring Framework, Liferay Portal, and Eclipse RCP), cloud computing technologies, cloud-based software architectures, enterprise application integration, and relational and NoSQL databases. Martin is one of the leaders of the Bulgarian Java Users group (BGJUG), a regular speaker at Java conferences, and one of the organizers behind the jPrime conference in Bulgaria (http://jprime.io/)., Table of Contents, Introducing RabbitMQDesign Patterns with RabbitMQAdministration, Confi guration, and ManagementClusteringHigh AvailabilityIntegrationsPerformance Tuning and MonitoringTroubleshootingSecurityInternalsContributing to RabbitMQ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值