<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client </artifactId> <version>5.7.0</version > </dependency>
1.简单队列
公共连接
package com.aynu.bootamqp.commons.utils; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Amqp { public static Connection getConnection() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); factory.setVirtualHost("/test"); factory.setUsername("mm"); factory.setPassword("123"); Connection connection = factory.newConnection(); return connection ; } }
2.发送者
package com.aynu.bootamqp.service; import com.aynu.bootamqp.commons.utils.Amqp; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Send { private final static String QUEUE_NAME ="hello"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = Amqp.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); String message = "hello mm"; channel.basicPublish("",QUEUE_NAME,null,message.getBytes("utf-8")); System.out.println("=="+message); channel.close(); connection.close(); } }
3.接受者
package com.aynu.bootamqp.service; import com.aynu.bootamqp.commons.utils.Amqp; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Receive { private final static String QUEUE_NAME ="hello"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = Amqp.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg = new String(body,"utf-8"); System.out.println("receive"+msg); } }; channel.basicConsume(QUEUE_NAME,true,consumer); } }