RabbitMQ + Springboot +“Hello Word”

https://www.rabbitmq.com/getstarted.html 

官网文档

(P) - > [|||]

我们将呼叫我们的消息发布者(发送者)发送和我们的消息消费者(接收者) Recv发布者将连接到RabbitMQ,发送单个消息,然后退出

创建一个Send.java 暂未再配置文件 配置 如下: 

    //设置类命名队列
    private final static String QUEUE_NAME = "hello";
    private static void main (String [] argv) throws Exception{
        //创建服务器的链接
        ConnectionFactory factory = new ConnectionFactory();
        //创建
        factory.setHost("XXX.XXX.XX.XX");
        factory.setPassword("guest");
        factory.setUsername("guest");
        factory.setPort(111);
        
        try{Connection connection = factory.newConnection();
            Channel channel = connection.createChannel() ;
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);

            String sendMessage = "暂未使用spring boot";
            //发送信息
            channel.basicPublish("",QUEUE_NAME,null,sendMessage.getBytes());



        }catch (Exception e){

        }



   }

 如果再springboot 配置文件配置

@Component
public class Send {
    //设置类命名队列
    private final static String QUEUE_NAME = "hello";

    @Value("${spring.rabbitmq.host}")
    private  String host;
    @Value("${spring.rabbitmq.port}")
    private  int port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;

    public void init(){
        //创建服务器的链接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setPort(port);
        factory.setPassword(password);
        factory.setUsername(username);
        factory.setHost(host);
        try{Connection connection = factory.newConnection();
            Channel channel = connection.createChannel() ;
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String value = "hello";
            channel.basicPublish("",QUEUE_NAME,null,value.getBytes());
        }catch (Exception e){

        }

    }
}

配置文件

########### rabbitmq  ############
spring.rabbitmq.host=XXX.xxx.xxx.xx
spring.rabbitmq.port=xxx
spring.rabbitmq.username=xxx
spring.rabbitmq.password=xxx

启动类

    @Override
    public void run(String... args) throws Exception {
        Send.init();
        
    }

项目启动后 到

 查看

发送的信息

 

猜你喜欢

转载自www.cnblogs.com/wudixiaoguaishou/p/11400162.html