SpringBoot笔记(十一)RabbitMQ

安装Erlang

RabbitMQ基于Erlang,所以得先安装Erlang

http://www.erlang.org/downloads

根据自己的系统选择下载,安装完了,配置一下path即可

windows默认安装路径:C:\Program Files\erl9.3\bin;

验证: erl -version

有时候可能需要重启才能生效

安装RabbitMQ

http://www.rabbitmq.com/install-windows.html

默认安装路径最好修改一下,因为RabbitMQ不支持带有空格的路径(需先安装Erlang)

安装RabbitMQ-Plugins

这个是管理界面,可以查看队列消息及各种信息

  • 进入rabbitmq的sbin目录
  • 输入rabbitmq-plugins enable rabbitmq_management命令(需server已启动 rabbitmq-service start)
  • 验证 http://localhost:15672
  • 用户名密码都是guest
rabbitmq_01.png

RabbitMQ的简单介绍

先看几个概念

  • producer:生产者

  • consumer:消费者

  • virtual host:虚拟主机

    • 在RabbitMQ中,用户只能在虚拟主机的层面上进行一些权限设置,比如可以访问哪些队列,可以处理哪些请求等
  • broker:消息转发者

    • 也就是我们RabbitMQ服务端充当的功能
    • exchange:交换机
      • 和producer直接打交道的,主要进行转发操作
    • queue:消息队列
      • 用于接收exchange路由过来的消息并存放

send

package com.jiataoyuan.demo.rabbitmq.config;

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

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/21 0021
 * @description producer 生产者
 *
 * (1):创建ConnectionFactory,并且设置一些参数,比如hostname,portNumber等等
 * (2):利用ConnectionFactory创建一个Connection连接
 * (3):利用Connection创建一个Channel通道
 * (4):创建queue并且和Channel进行绑定
 * (5):创建消息,并且发送到队列中
 *
 * 本例没有用到exchange交换机,RabbitMQ默认情况下是会创建一个空字符串名字的exchange
 * 如果我们没有创建自己的exchange的话,默认就是使用的这个exchange
 */
public class Send {
    private final static String QUEUE_NAME = "MyQueue";

    public static void main(String[] args) {
        send();
    }

    public static void send()
    {
        ConnectionFactory factory = null;
        Connection connection = null;
        Channel channel = null;
        try {
            factory = new ConnectionFactory();
            factory.setHost("127.0.0.1");
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            String message = "Send MyQueue send message .....";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            System.out.println("已经发送消息....."+message);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            try {
                //关闭资源
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}

receive

package com.jiataoyuan.demo.rabbitmq.config;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/21 0021
 * @description consumer 消费者
 *
 * (1):创建ConnectionFactory,并且设置一些参数,比如hostname,portNumber等等
 * (2):利用ConnectionFactory创建一个Connection连接
 * (3):利用Connection创建一个Channel通道
 * (4):将queue和Channel进行绑定,注意这里的queue名字要和前面producer创建的queue一致
 * (5):创建消费者Consumer来接收消息,同时将消费者和queue进行绑定
 *
 */
public class Receive {
    private final static String QUEUE_NAME = "MyQueue";

    public static void main(String[] args) {
        receive();
    }

    public static void receive()
    {
        ConnectionFactory factory = null;
        Connection connection = null;
        Channel channel = null;

        try {
            factory = new ConnectionFactory();
            factory.setHost("localhost");
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                    String message = new String(body, "UTF-8");
                    System.out.println("收到消息....."+message);
                }
            };


            channel.basicConsume(QUEUE_NAME, true,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally{
            try {
                //关闭资源
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}

做测试的时候,可以先发送,不接收,然后去 http://localhost:15672/#/queues 看看。

SpringBoot整合RabbitMQ

以上就是RabbitMQ的基本用法,接下来还是要整合到SpringBoot中使用。

依赖


    org.springframework.boot
    spring-boot-starter-amqp

配置

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.virtual-host=/

RabbitMQ模式有很多,还是演示一下最简单的模式,实际开发过程中可以根据业务选择最适合的业务场景

Sender

package com.jiataoyuan.demo.rabbitmq.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Administrator on 2017/5/8 0008.
 */
@Component
public class Sender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendData(String data){
        if (null == data){
            data = "data is null! Time: " + new Date();
        }
        System.out.println("Sender : " + data);
        rabbitTemplate.convertAndSend("hello", data);
    }

}

Receive

package com.jiataoyuan.demo.rabbitmq.config;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/21 0021
 * @description description
 */
@Component
@RabbitListener(queues = "hello")
public class Receive {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }
}

Controller

package com.jiataoyuan.demo.rabbitmq.controller;

import com.jiataoyuan.demo.rabbitmq.config.Sender;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/21 0021
 * @description description
 */
@RestController
@RequestMapping("/rabbit")
public class RabbitMQController {

    @Resource
    private Sender sender;


    @GetMapping()
    public String Main(){
        return "

hello RabbitMQ!

"; } @GetMapping("/send") public String Send() throws Exception{ sender.sendData("Hello, This is OneToOne!"); return "Send OK!"; } }

result

Sender : Hello, This is OneToOne!
Receiver  : Hello, This is OneToOne!

你可能感兴趣的:(SpringBoot笔记(十一)RabbitMQ)