Spring Boot 搭配 RabbitMQ 使用(简单模式,工作模式,订阅模式,路由模式,主题模式)

第一步导入依赖:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.7.3</version>
</dependency>

1.简单模式连接:

发布者代码:

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

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

public class Providers {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 消息发布者
        * */
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        //地址
        factory.setHost("192.168.17.8");
        //用户的【Can access virtual hosts】值
        factory.setVirtualHost("/");
        //服务器端口
        factory.setPort(5672);
        //用户名
        factory.setUsername("guest");
        //密码
        factory.setPassword("llh123456");
        //获取连接
        Connection connection = factory.newConnection();
        //创建频道
        Channel channel = connection.createChannel();
        //申明队列(对列名称,是否持久化,是否独占频道,是否自动销毁,其他参数Map集合)
        channel.queueDeclare("First_llh",true,false,false,null);
        //设置消息
        String massges = "hellow rabbitmq";
        //发送消息(对列名称,BasicProperties基础配置,消息的字节数组)
        channel.basicPublish("","First_llh",null,massges.getBytes());
        //关闭频道
        channel.close();
        //关闭连接
        connection.close();
    }
}

接收者代码:

import com.rabbitmq.client.*;
import util.RabbitConnection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Conmmons {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 接收者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("192.168.17.8", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();
        //接受消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //获取消息(delivery.getBody() = [B@4322ce5)然后设置编码UTF_8编码,在转换string类型
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("massges:[" + message +"]");
        };
        //对列名称,是否持久化,
        channel.basicConsume("First_llh",true,deliverCallback,(consumerTag)->{});
    }
}

考虑到创建连接的代码冗余:

写一个连接的工具类

package util;

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

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

public class RabbitConnection {
    public static Connection getConection(String host,String SSL,Integer port,String user,String pwd) throws IOException, TimeoutException {
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        //地址
        factory.setHost(host);
        //用户的【Can access virtual hosts】值
        factory.setVirtualHost(SSL);
        //服务器端口
        factory.setPort(port);
        //用户名
        factory.setUsername(user);
        //密码
        factory.setPassword(pwd);
        //获取连接
        Connection connection = factory.newConnection();
        return connection;
    }
}

调用工具类获取连接

 //获取连接
Connection geust = RabbitConnection.getConection("192.168.17.8", "/", 5672, "guest", "llh123456");

注:接收者启动会监视队列是否发送了新的消息,实时刷新的


2.工作模式连接:

发布者代码:

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

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

public class Providers {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 消息发布者
        * */
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        //地址
        factory.setHost("192.168.17.8");
        //用户的【Can access virtual hosts】值
        factory.setVirtualHost("/");
        //服务器端口
        factory.setPort(5672);
        //用户名
        factory.setUsername("guest");
        //密码
        factory.setPassword("llh123456");
        //获取连接
        Connection connection = factory.newConnection();
        //创建频道
        Channel channel = connection.createChannel();
        //申明队列(对列名称,是否持久化,是否独占频道,是否自动销毁,其他参数Map集合)
        channel.queueDeclare("First_llh",true,false,false,null);
        //设置消息
        String massges = "hellow rabbitmq";
        //发送消息(对列名称,BasicProperties基础配置,消息的字节数组)
        channel.basicPublish("","First_llh",null,massges.getBytes());
        //关闭频道
        channel.close();
        //关闭连接
        connection.close();
    }
}

接收者1类代码

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import util.RabbitConnection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ConmmonsTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 接收者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("192.168.17.8", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();
        //接受消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //获取消息(delivery.getBody() = [B@4322ce5)然后设置编码UTF_8编码,在转换string类型
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("massges:[" + message +"]");
        };
        //对列名称,是否持久化,
        channel.basicConsume("First_llh",true,deliverCallback,(consumerTag)->{});
    }
}

接收者2类代码

import com.rabbitmq.client.*;
import util.RabbitConnection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Conmmons {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 接收者2
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("192.168.17.8", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();
        //接受消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //获取消息(delivery.getBody() = [B@4322ce5)然后设置编码UTF_8编码,在转换string类型
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("massges:[" + message +"]");
        };
        //对列名称,是否持久化,
        channel.basicConsume("First_llh",true,deliverCallback,(consumerTag)->{});
    }
}

注:工作模式下对列会均匀分配资源

1.同时运行 接收者1类 和 接收者2类

发送10条数据

 读取者1的结果

读取者2的结果


3.订阅模式:

发布者代码:

package com.guigu.www.exchange;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

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

public class ExchangeProviders {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 订阅模式消息发布者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");

        //创建频道
        Channel channel = geust.createChannel();

        //申明队列(对列名称,是否持久化,是否独占频道,是否自动销毁,其他参数Map集合)
        channel.queueDeclare("exchange1",true,false,false,null);
        channel.queueDeclare("exchange2",true,false,false,null);

        //申明交换机
        /*DIRECT("direct") 路由模式
        * FANOUT("fanout") 订阅模式
        * TOPIC("topic") 主题模式
        * */
        channel.exchangeDeclare("exchange_name", BuiltinExchangeType.FANOUT);

        //将队列和交换机进行绑定
        //(队列名,交换机名,路由key)
        channel.queueBind("exchange1","exchange_name","");
        channel.queueBind("exchange2","exchange_name","");

        //设置消息
        String massges = "订阅模式配置成功";
        //发送消息(交换机名称,路由key,消息路由头等的其他属性 ,消息的字节数组)
        channel.basicPublish("exchange_name","",null,massges.getBytes());

        //关闭频道
        channel.close();
        //关闭连接
        geust.close();
    }
}

接收者1类代码:

package com.guigu.www.exchange;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class ExchangeConmmons {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 订阅模式接收者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("exchange1",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:"+consumerTag);
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

接收者2类代码:

package com.guigu.www.exchange;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class ExchangeConmmonsTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
         * 订阅模式接收者2
         * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("exchange2",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //生成一个消费者标签,对消费者进行唯一标识
                System.out.println("consumerTag:"+consumerTag);
                //可以通过envelope获取exchange和routingkey信息
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                //获取信息
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

4.路由模式:

发布者代码:

package com.guigu.www.route;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

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

public class RouteProviders {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 路由模式消息发布者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");

        //创建频道
        Channel channel = geust.createChannel();

        //申明队列(对列名称,是否持久化,是否独占频道,是否自动销毁,其他参数Map集合)
        channel.queueDeclare("route1",true,false,false,null);
        channel.queueDeclare("route2",true,false,false,null);

        //申明交换机
        /*DIRECT("direct") 路由模式
        * FANOUT("fanout") 订阅模式
        * TOPIC("topic") 主题模式
        * */
        channel.exchangeDeclare("route_exchange", BuiltinExchangeType.DIRECT);

        //将队列和交换机进行绑定
        //(队列名,交换机名,路由key)
        channel.queueBind("route1","route_exchange","insert");
        channel.queueBind("route2","route_exchange","delete");

        //设置消息
        String massges = "路由模式配置成功{增}";
        String massges2 = "路由模式配置成功{删}";
        //发送消息(交换机名称,路由key,消息路由头等的其他属性 ,消息的字节数组)
        channel.basicPublish("route_exchange","insert",null,massges.getBytes());
        channel.basicPublish("route_exchange","delete",null,massges2.getBytes());

        //关闭频道
        channel.close();
        //关闭连接
        geust.close();
    }
}

接收者1类代码:

package com.guigu.www.route;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class RouteConmmons {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 路由模式接收者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("route1",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:"+consumerTag);
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

运行结果:

接收者2类代码:

package com.guigu.www.route;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class RouteConmmonsTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
         * 路由模式接收者2
         * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("route2",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //生成一个消费者标签,对消费者进行唯一标识
                System.out.println("consumerTag:"+consumerTag);
                //可以通过envelope获取exchange和routingkey信息
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                //获取信息
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

运行结果:

5.主题模式:

  

发布者代码:

package com.guigu.www.theme;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

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

public class ThemeProviders {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 主题模式消息发布者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");

        //创建频道
        Channel channel = geust.createChannel();

        //申明队列(对列名称,是否持久化,是否独占频道,是否自动销毁,其他参数Map集合)
        channel.queueDeclare("theme1",true,false,false,null);
        channel.queueDeclare("theme2",true,false,false,null);

        //申明交换机
        /*DIRECT("direct") 路由模式
        * FANOUT("fanout") 订阅模式
        * TOPIC("topic") 主题模式
        * */
        channel.exchangeDeclare("theme_exchange", BuiltinExchangeType.TOPIC);

        //将队列和交换机进行绑定
        //(队列名,交换机名,路由key【*是下面的一级,#是下面的所有】)
        channel.queueBind("theme1","theme_exchange","business.*");
        channel.queueBind("theme2","theme_exchange","business2.#");

        //设置消息
        String massges = "主题模式配置成功{business增}";
        String massges2 = "主题模式配置成功{business删}";
        String massges3 = "主题模式配置成功{business改}";
        String massges4 = "主题模式配置成功{business查}";

        String massges5 = "主题模式配置成功{business2增}";
        //发送消息(交换机名称,路由key,消息路由头等的其他属性 ,消息的字节数组)
        channel.basicPublish("theme_exchange","business.c",null,massges.getBytes());
        channel.basicPublish("theme_exchange","business.d",null,massges2.getBytes());
        channel.basicPublish("theme_exchange","business.u",null,massges3.getBytes());
        channel.basicPublish("theme_exchange","business.test.r",null,massges4.getBytes());

        channel.basicPublish("theme_exchange","business2.user.c",null,massges5.getBytes());


        //关闭频道
        channel.close();
        //关闭连接
        geust.close();
    }
}

接收者1类代码:

package com.guigu.www.theme;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class ThemeConmmons {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
        * 路由模式接收者
        * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("theme1",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag:"+consumerTag);
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

运行结果:

接收者2类代码:

package com.guigu.www.theme;

import com.guigu.www.util.RabbitConnection;
import com.rabbitmq.client.*;

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

public class ThemeConmmonsTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        /*
         * 路由模式接收者
         * */
        //获取连接
        Connection geust = RabbitConnection.getConection("172.20.10.7", "/", 5672, "guest", "llh123456");
        //创建频道
        Channel channel = geust.createChannel();

        //(交换机名称,自动回调,回调方法)
        channel.basicConsume("theme2",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //生成一个消费者标签,对消费者进行唯一标识
                System.out.println("consumerTag:"+consumerTag);
                //可以通过envelope获取exchange和routingkey信息
                System.out.println(envelope.getExchange()+"\t"+envelope.getRoutingKey()+"\t"+envelope.getDeliveryTag());
                //获取信息
                System.out.println(new String(body,"UTF-8"));
            }
        });
    }
}

运行结果:

 源码链接,仅供学习参考!!!

javaRabbitMQ.zip - 蓝奏云文件大小:44.8 K|https://llh317.lanzout.com/i4tARy8r3xa

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值