java项目 rabbit的简单搭建,使用rabbitmq queue的简单例子和一些坑

一 整合

由于本人的码云太多太乱了,于是决定一个一个的整合到一个springboot项目里面。

附上自己的项目地址https://github.com/247292980/spring-boot

 

以整合功能

spring-boot,FusionChart,thymeleaf,vue,ShardingJdbc,mybatis-generator,微信分享授权,drools,spring-security,spring-jpa,webjars,Aspect,drools-drt

 

这次就来整合下简单的rabbitmq

 

二 安装

这玩意最坑的地方在于,百度第一的安装教程,缺了一部分。

 

1.安装erlong,搭建环境变量
2.安装mq
3.这里他有一个mq管理插件的东西,我只想说这玩意很老了,新的mq基本都自己装了, http://localhost:15672 你能打开就是已经装成功,所以xxx plugin unchange的其实是没有错的。


或许有人用老板的我也贴一下相应代码,以下所有命令默认cd到mq的sbin目录下

enable rabbitmq_management


4.查询用户

rabbitmqctl.bat list_users

 

5.新增一个用户

rabbitmqctl.bat add_user username password
例子 rabbitmqctl.bat add_user haha
123456798

6.更改角色

rabbitmqctl.bat set_user_tags username role

例子
rabbitmqctl.bat set_user_tags haha administrator

7.改密码

rabbitmqctl change_password userName newPassword

例子
rabbitmqctl change_password haha 123456

8.删除用户

rabbitmqctl.bat delete_user username

例子
rabbitmqctl.bat delete_user haha

9.设置用户权限

rabbitmqctl  set_permissions  -p  VHostPath  User  ConfP  WriteP  ReadP

例子 这个例子一定要跑一下,百度第一的照着做会报你没有权限的error,授予用户username在服务器根目录辖所有资源的读写权限
rabbitmqctl.bat set_permissions -p "/" haha ".*" ".*" ".*"

10.查看(指定hostpath)所有用户的权限信息

rabbitmqctl  list_permissions  [-p  VHostPath]

11.查看指定用户的权限信息

rabbitmqctl  list_user_permissions  User

例子
rabbitmqctl  list_user_permissions  haha

12.清除用户的权限信息

rabbitmqctl  clear_permissions  [-p VHostPath]  User

例子
rabbitmqctl  clear_permissions  [-p VHostPath]  haha

 

13.在写demo之前,我们还要做一个事情,添加一个队列,进入http://localhost:15672点击queues标签即能看到

 

三 代码

生产者

/**
 * @AUTHOR lgp
 * @DATE 2018/9/7 17:27
 * @DESCRIPTION rabbitmq的消息生产者
 **/
public class Producer {
    public final static String QUEUE_NAME = "rabbitMQ.lgp";
    public static final Logger log = LoggerFactory.getLogger(Producer.class);

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置RabbitMQ相关信息
        factory.setHost("localhost");
        factory.setUsername("haha");
        factory.setPassword("123456789");
        factory.setPort(5672);
        //创建一个新的连接
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //创建一个通道
            //  声明一个队列
//            public com.rabbitmq.client.AMQP.Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) throws IOException
            boolean durable = true;
            boolean exclusive = false;
            boolean auto_delete = false;
//            Map<String, Object> arguments = new HashMap<String, Object>();
//            // 统一设置队列中的所有消息的过期时间
//            arguments.put("x-message-ttl", 30000);
//            // 设置超过多少毫秒没有消费者来访问队列,就删除队列的时间
//            arguments.put("x-expires", 20000);
//            // 设置队列的最新的N条消息,如果超过N条,前面的消息将从队列中移除掉
//            arguments.put("x-max-length", 4);
//            // 设置队列的内容的最大空间,超过该阈值就删除之前的消息
//            arguments.put("x-max-length-bytes", 1024);
//            // 将删除的消息推送到指定的交换机,一般x-dead-letter-exchange和x-dead-letter-routing-key需要同时设置
//            arguments.put("x-dead-letter-exchange", "exchange.dead");
//            // 将删除的消息推送到指定的交换机对应的路由键
//            arguments.put("x-dead-letter-routing-key", "routingkey.dead");
//            // 设置消息的优先级,优先级大的优先被消费
//            arguments.put("x-max-priority", 10);
            channel.queueDeclare(QUEUE_NAME, durable, exclusive, auto_delete, null);
            String message = "Hello RabbitMQ";
            //发送消息到队列中
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            log.info("Producer Send message={}", message);
            //关闭通道和连接
            channel.close();
        }

    }
}

消费者

/**
 * @AUTHOR lgp
 * @DATE 2018/9/7 17:34
 * @DESCRIPTION 消费者
 **/
public class Customer {
    private final static String QUEUE_NAME = "rabbitMQ.lgp";
    public static final Logger log = LoggerFactory.getLogger(Customer.class);

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置RabbitMQ地址
        factory.setHost("localhost");
        factory.setUsername("haha");
        factory.setPassword("123456789");
        factory.setPort(5672);
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            //创建一个通道
            //声明要关注的队列
            //队列持久化,在RabbitMQ重启保证队列不会丢失
            boolean durable = true;
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            System.out.println("Customer Waiting Received messages");
            //DefaultConsumer类实现了Consumer接口,通过传入一个频道,
            // 告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
            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");
                    log.info("Customer Received message={}", message);
                }
            };
            //自动回复队列应答 -- RabbitMQ中的消息确认机制
            channel.basicConsume(QUEUE_NAME, true, consumer);
        }
    }
}

四 注意点

1.我为了测试queueDeclare的参数代表的是什么意思,起了什么作用(由于多次测试,也出现了下面这些奇奇怪怪的bug),发现exclusive 和auto_delete的报错都是说auto_delete,但是具体的作用就是不同,所以你懂得...

2.还有一个谜一样的bug,我能上http://localhost:15672,但是java代码死活不行,那我看看cmd正不正常,然后

Error: unable to perform an operation on node 'rabbit@haha'. Please see diagnostics information and suggestions below.

Most common reasons for this are:

 * Target node is unreachable (e.g. due to hostname resolution, TCP connection or firewall issues)
 * CLI tool fails to authenticate with the server (e.g. due to CLI tool's Erlang cookie not matching that of the server)
 * Target node is not running

In addition to the diagnostics info below:

 * See the CLI, clustering and networking guides on http://rabbitmq.com/documentation.html to learn more
 * Consult server logs on node rabbit@haha

DIAGNOSTICS
===========

attempted to contact: [rabbit@haha]

rabbit@haha:
  * connected to epmd (port 4369) on haha
  * epmd reports node 'rabbit' uses port 25672 for inter-node and CLI tool traffic
  * TCP connection succeeded but Erlang distribution failed

  * Hostname mismatch: node "rabbit@xxxx" believes its host is different. Please ensure that hostnames resolve the same way locally and on "rabbit@xxxx"


Current node details:
 * node name: rabbitmqcli30@haha
 * effective user's home directory: C:\Users\xxxx
 * Erlang cookie hash: 0rVZh7WgaAP8H8hmZPiGLA==

就是说,node没创建?我都用haha登上你的web管理系统啊???

这报错莫名其妙的出现了我电脑的名字,,,,

看情况就是node rabbit@xxxx这玩意是mq底层取参数,取到了电脑的名字去了?然后两个mabbit都启动erlang,erlang抢夺端口的error??

 

解决方法 删除所有mq线程,重启mq

3.同样是一个谜一样的bug,启动rabbit成功,但是java还是不同跑

Error: unable to perform an operation on node 'rabbit@haha'. Please see diagnostics information and suggestions below.

Most common reasons for this are:

 * Target node is unreachable (e.g. due to hostname resolution, TCP connection or firewall issues)
 * CLI tool fails to authenticate with the server (e.g. due to CLI tool's Erlang cookie not matching that of the server)
 * Target node is not running

In addition to the diagnostics info below:

 * See the CLI, clustering and networking guides on http://rabbitmq.com/documentation.html to learn more
 * Consult server logs on node rabbit@haha

DIAGNOSTICS
===========

attempted to contact: [rabbit@haha]

rabbit@haha:
  * connected to epmd (port 4369) on haha
  * epmd reports: node 'rabbit' not running at all
                  no other nodes on haha
  * suggestion: start the node

Current node details:
 * node name: rabbitmqcli26@haha
 * effective user's home directory: C:\Users\xxxx
 * Erlang cookie hash: 0rVZh7WgaAP8H8hmZPiGLA==

node没有创建,那么不是重启rabbitmq这个层次的问题啊...

 

解决方法

在windows的服务里面重启rabbitmq的服务,出现这问题的原因可能是我开了两个cmd操作rabbitmq,搞到erlang线程死锁了,,,,

4.代码里我只写了mq的简单应用,比较核心的如分发,订阅等我都没有写,因为用过mq的都知道,这些东西其实都是一样的简单的(像我测试queueDeclare那样一个一个改一个一个看具体作用,好蠢是不是...),主要是设计思路.所以我就不写其他的例子,只写了消息队列中的简单队列。

5.这个是上面两个的低配版。error node with name "rabbit" already running on “xxxxxxx”

一看就知道重启mq就行了

 

posted @ 2018-09-10 10:59  lgp20151222  阅读(3586)  评论(0编辑  收藏  举报