RabbitMQ简单消息发送

发布于:2025-07-02 ⋅ 阅读:(45) ⋅ 点赞:(0)

RabbitMQ简单消息发送

简单代码实现RabbitMQ消息发送

需要的依赖

        <!--rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
            <version>x.x.x</version>
        </dependency>

消息发送示例

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Slf4j
public class RabbitMQConfig2 {

    private static  String addresses = "localhost:5672";
    private static String username = "xxx";
    private static String password = "xxx";




    public static   void testSendMessage() throws IOException, TimeoutException {
        System.out.println("发送消息");
        // 1.建立连接
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setAddresses(addresses);
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setVirtualHost("/");
        // 1.2.建立连接
        Connection connection = factory.createConnection();

        // 2.创建通道Channel
        Channel channel = connection.createChannel(true);

        // 3.创建队列
		/*
            声明队列
                参数1:队列的名称 queueName
                参数2:队列是否支持持久化 false:不持久化处理
                参数3:队列是否排它:是否允许其它的connection下的channel连接
                参数4:是否空闲时自动删除,当最后一个consumer(消费者)断开之后,队列将自动删除。
                参数5:参数是rabbitmq的一个扩展,功能非常强大,基本是AMPQ中没有的。
         */
        String queueName = "queue1";
        channel.queueDeclare(queueName, false, false, false, null);

        // 4.发送消息
        String message = "hello, rabbitmq!";
        /*
            发送消息:
                参数1:exchange 交换机 没有就设置为 "" 值就可以了
                参数2:routingKey 路由的key 现在没有设置key,直接使用队列的名字queueName
                参数3:发送数据到队列的时候,是否要带一些参数。直接赋值null即可
                参数4:body 向队列中发送的消息数据
         */
        channel.basicPublish("", queueName, null, message.getBytes());
        System.out.println("发送消息成功:【" + message + "】");

        // 5.关闭通道和连接
        channel.close();
        connection.close();

    }

}

网站公告

今日签到

点亮在社区的每一天
去签到