Java连接Rabbitmq及connection error问题解决


Java连接Rabbitmq及connection error问题解决

😀 1.构建一个maven工程

image-20210629143822188

😁 2.导入rabbitmq的maven依赖

进入网址下载,按自己的要求选择https://mvnrepository.com/artifact/com.rabbitmq/amqp-client

image-20210629144903756

进行人机验证后搜索rabbitmq

image-20210629145436183

找一个下载量多的复制代码到 pom.xml 文件下

image-20210629145717498

😡 如有报错not found

image-20210629150211138

image-20210629150340369

😡 下面的依赖如果不弄连接时会报错:“ SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder

解决办法:https://www.cnblogs.com/chuchukuoai/p/14946028.html


😘 3.Java连接Rabbitmq

package com.rabbitmq.simple; # 前面没弄依赖这里会报错
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

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

public class Producer {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(""); # 用自己的地址就好了
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/"); # setvirtualhost可自行修改,但是要去RabbitMQ服务端修改权限,不然会报错
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();
            String queueName = "queuel";
            channel.queueDeclare(queueName, false, false, false, null);
            String message = "hello";
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                if (connection != null && connection.isOpen()) {
                    try {
                        connection.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }

        }
    }
}


😆 4.点击运行去RabbitMQ服务端查看结果即可

image-20210629151302748


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM