美文网首页
RabbitMQ生产者示例代码

RabbitMQ生产者示例代码

作者: 吕小凯 | 来源:发表于2019-07-08 18:44 被阅读0次
package com.xk.provider;

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

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

public class ProducerDemo {
    private static final String EXCHANGE_NAME="exchange_demo";
    private static final String ROUTING_KEYY="routingkey_demo";
    private static final String QUEUE_NAME="queue_demo";
    private static final String IP_ADDRESS="192.168.0.2";
    private static final int PORT=5672;//RabbitMQ服务端默认端口号为5672
    private static final String USERNAME="root";
    private static final String PASSWORD="root";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
        Connection connection = factory.newConnection();//创建连接
        Channel channel = connection.createChannel();//创建信道
        //创建type="direct".持久化的非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME,"direct",true,false,null);
        //创建一个持久化 非排他的 非自动删除的队列
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        //将交互器与队列经过路由键绑定
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,ROUTING_KEYY);
        //发送一条持久化的消息 Hello,RabbitMQ!
        String Message = "Hello,RabbitMQ!";
        channel.basicPublish(EXCHANGE_NAME,ROUTING_KEYY, MessageProperties.PERSISTENT_TEXT_PLAIN,Message.getBytes());
        //关闭资源
        channel.close();
        connection.close();
    }
}

相关文章

网友评论

      本文标题:RabbitMQ生产者示例代码

      本文链接:https://www.haomeiwen.com/subject/ptfxkctx.html