rabbitMq之:Hello World!详解编程语言

本文章主要介绍了rabbitMq之:Hello World!,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!

pom.xml
jar包

    <dependency> 
      <groupId>com.rabbitmq</groupId> 
      <artifactId>amqp-client</artifactId> 
      <version>3.5.6</version> 
    </dependency> 
     <dependency> 
      <groupId>commons-lang</groupId> 
      <artifactId>commons-lang</artifactId> 
      <version>2.6</version> 
    </dependency>

发送消息:Send.java
RabbitMqParm.HOST如果把rabbitMq装在本机了,就写“localhost”,本人把rabbitMq搭在阿里云服务器了,所以就是相应的外网ip

import com.rabbitmq.client.Channel; 
import com.rabbitmq.client.Connection; 
import com.rabbitmq.client.ConnectionFactory; 
import com.zheng.model.RabbitMqParm; 
 
public class Send { 
    private final static String QUEUE_NAME = "simple-queue"; 
 
    public static void main(String[] argv) throws java.io.IOException, TimeoutException { 
        ConnectionFactory factory = new ConnectionFactory(); 
        factory.setHost(RabbitMqParm.HOST); 
 
        Connection connection = connection = factory.newConnection(); 
        Channel channel = connection.createChannel(); 
 
        channel.queueDeclare(QUEUE_NAME, false, false, false, null); 
        String message = "Hello world!"; 
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 
        System.out.println("发送的消息:" + message + "'"); 
 
        channel.close(); 
        connection.close(); 
    } 
}

接收消息:Recv.java

import com.rabbitmq.client.*; 
import com.zheng.model.RabbitMqParm; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
 
import java.io.IOException; 
import java.util.concurrent.TimeoutException; 
 
public class Recv {
    
    private static final Logger logger = LoggerFactory.getLogger(Recv.class); 
 
    private final static String QUEUE_NAME = "simple-queue"; 
 
    public static void main(String[] argv) throws TimeoutException, IOException { 
 
        ConnectionFactory factory = new ConnectionFactory(); 
        factory.setHost(RabbitMqParm.HOST); 
        Connection connection = factory.newConnection();//建立tcp连接 
        Channel channel = connection.createChannel(); 
 
        channel.queueDeclare(QUEUE_NAME, false, false, false, null); 
 
        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"); 
                System.out.println("接收到的消息" + message ); 
            } 
        }; 
        channel.basicConsume(QUEUE_NAME, true, consumer); 
    } 
}

运行Send.java后,到IT虾米网 界面可看到已经创建了一个名为simple-queue的queue
这里写图片描述

点进去,看到有消息发送过来:
这里写图片描述

启动Recv.java以后,消息被消费:
这里写图片描述

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/228218.html

(0)
上一篇 2022年1月11日
下一篇 2022年1月11日

相关推荐

发表回复

登录后才能评论