准备工作

  • 15min
  • IDEA
  • maven 3.0

在开始构建项目之前,机器需要安装rabbitmq,你可以去官网下载,http://www.rabbitmq.com/download.html ,如果你是用的Mac(程序员都应该用mac吧),你可以这样下载:

1
brew install rabbitmq

  

安装完成后开启服务器:

1
rabbitmq-server

  

开启服务器成功,你可以看到以下信息:

1
2
3
4
5
6
7
           RabbitMQ 3.1.3. Copyright (C) 2007-2013 VMware, Inc.
##  ##      Licensed under the MPL.  See http://www.rabbitmq.com/
##  ##
##########  Logs: /usr/local/var/log/rabbitmq/rabbit@localhost.log
######  ##        /usr/local/var/log/rabbitmq/rabbit@localhost-sasl.log
##########
            Starting broker... completed with 6 plugins.

  

构建工程

构架一个SpringBoot工程,其pom文件依赖加上spring-boot-starter-amqp的起步依赖:

1
2
3
4
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

  

创建消息接收者

在任何的消息队列程序中,你需要创建一个消息接收者,用于响应发送的消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
public class Receiver {
 
    private CountDownLatch latch = new CountDownLatch(1);
 
    public void receiveMessage(String message) {
        System.out.println("Received <" + message + ">");
        latch.countDown();
    }
 
    public CountDownLatch getLatch() {
        return latch;
    }
 
}

  

消息接收者是一个简单的POJO类,它定义了一个方法去接收消息,当你注册它去接收消息,你可以给它取任何的名字。其中,它有CountDownLatch这样的一个类,它是用于告诉发送者消息已经收到了,你不需要在应用程序中具体实现它,只需要latch.countDown()就行了。

创建消息监听,并发送一条消息

在spring程序中,RabbitTemplate提供了发送消息和接收消息的所有方法。你只需简单的配置下就行了:

  • 需要一个消息监听容器
  • 声明一个quene,一个exchange,并且绑定它们
  • 一个组件去发送消息

代码清单如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.forezp;
 
import com.forezp.message.Receiver;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
 
 
@SpringBootApplication
public class SpringbootRabbitmqApplication {
 
     final static String queueName = "spring-boot";
 
    @Bean
    Queue queue() {
        return new Queue(queueName, false);
    }
 
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("spring-boot-exchange");
    }
 
    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }
 
    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                             MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }
 
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
 
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootRabbitmqApplication.class, args);
    }
}

  

创建一个测试方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component
public class Runner implements CommandLineRunner {
 
    private final RabbitTemplate rabbitTemplate;
    private final Receiver receiver;
    private final ConfigurableApplicationContext context;
 
    public Runner(Receiver receiver, RabbitTemplate rabbitTemplate,
            ConfigurableApplicationContext context) {
        this.receiver = receiver;
        this.rabbitTemplate = rabbitTemplate;
        this.context = context;
    }
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Sending message...");
        rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
        receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);
        context.close();
    }
 
}

  

启动程序,你会发现控制台打印:

1
2
Sending message...
Received <Hello from RabbitMQ!>

  

关于RabbitMQ服务器整合(二)的更多相关文章

  1. Spring Boot教程(二)关于RabbitMQ服务器整合

    准备工作 15min IDEA maven 3.0 在开始构建项目之前,机器需要安装rabbitmq,你可以去官网下载,http://www.rabbitmq.com/download.html ,如 ...

  2. Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块

    Python第十三天   django 1.6   导入模板   定义数据模型   访问数据库   GET和POST方法    SimpleCMDB项目   urllib模块   urllib2模块 ...

  3. RabbitMQ学习系列二-C#代码发送消息

    RabbitMQ学习系列二:.net 环境下 C#代码使用 RabbitMQ 消息队列 http://www.80iter.com/blog/1437455520862503 上一篇已经讲了Rabbi ...

  4. RabbitMQ官方教程二 Work Queues(GOLANG语言实现)

    RabbitMQ官方教程二 Work Queues(GOLANG语言实现) 在第一个教程中,我们编写了程序来发送和接收来自命名队列的消息. 在这一部分中,我们将创建一个工作队列,该队列将用于在多个wo ...

  5. FastDFS搭建单机图片服务器(二)

    防丢失转载:https://blog.csdn.net/MissEel/article/details/80856194 根据 分布式文件系统 - FastDFS 在 CentOS 下配置安装部署 和 ...

  6. RabbitMQ小记(二)

    1.RabbitMQ相关介绍 (1)RabbitMQ整体上是一个生产者和消费者模型,主要负责接收.存储.转发消息.RabbitMQ整体结构图如下: (2)生产者:发送消息的一方,生产者创建一条消息,发 ...

  7. JAVA+PHP+阿里云组件纯手工实现POP、SMTP、IMAP开发邮件服务器(二)

    java开发邮件服务器的接收模块 用java建立socket服务端,监听端口25,实现SMTP协议.即可完成邮件服务器的接收模块. 这里要注意的是,SMTP协议其实可以分为两种.一种是你用手机.PC等 ...

  8. Windows 下安装RabbitMQ服务器及基本配置

    RabbitMQ是一个在AMQP协议标准基础上完整的,可复用的企业消息系统.它遵循Mozilla Public License开源协议,采用 Erlang 实现的工业级的消息队列(MQ)服务器,Rab ...

  9. 2. RabbitMQ 服务器 之下载安装

    RabbitMQ服务器如何安装? RabbitMQ是一个AMQP(Advanced Message Queue,即高级消息队列协议)服务器 . 下载地址: RabbitMQ下载 安装说明:各平台下Ra ...

随机推荐

  1. 获取IP及判断IP是否在区间

    /// <summary> /// 获取客户端IP /// </summary> /// <returns></returns> public stat ...

  2. 【BZOJ】1052: [HAOI2007]覆盖问题

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1052 大概自己YY了个贪心然后过了... 二分答案,考虑如何check: 找到一个最小的矩 ...

  3. 关于spring boot启动监控端点的方法(spring-boot-starter-actuator)

    前言: 在spring boot的旧版本中,监控端点(如/env)是默认开启的,所以只要项目正常启动,就能通过url获取信息.可是在2.0版本以后,由于安全性考虑,除了/health和/info的端点 ...

  4. Git 基础 - 打标签

    列出现有标签(或者使用git tag -l) $ git tag v0. v1. 如果只对 1.4.2 系列的版本感兴趣 $ git tag -l 'v1.4.2.*' v1. v1. v1. v1. ...

  5. Linux下的压缩解压缩命令详解及实例

    实例:压缩服务器上当前目录的内容为xxx.zip文件 zip -r xxx.zip ./* 解压zip文件到当前目录 unzip filename.zip ====================== ...

  6. 学Hadoop还是Spark好?

    JS 相信看这篇文章的你们,都和我一样对Hadoop和Apache Spark的选择有一定的疑惑,今天查了不少资料,我们就来谈谈这两种 平台的比较与选择吧,看看对于工作和发展,到底哪个更好. 一.Ha ...

  7. echarts 拼图和折线图的封装 及常规处理

    1.html <div id="wrap"></div> 2.js ; (function ($) { $.fn.extend({ echartsPie: ...

  8. linux c/c++ 文件是否存在

    linux c/c++ 文件是否存在 #include <unistd.h> int FileExist(const char* fname) { return access(fname, ...

  9. Eclipse项目左侧调整显示或者不显示路径

    View Menu(倒三角)-->Package Presentation-->选择Flat或Hierarchical

  10. Asp.net core 学习笔记 ( Area and Feature folder structure 文件结构 )

    2017-09-22 refer : https://msdn.microsoft.com/en-us/magazine/mt763233.aspx?f=255&MSPPError=-2147 ...