引入依赖
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.4.3</version>
</dependency>
</dependencies>
创建RabbitMQUtil
package utils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @auther gsj
* @create 2021-04-29-17:24
*/
public class RabbitMQUtil {
private static ConnectionFactory connectionFactory;
static{
connectionFactory = new ConnectionFactory();
connectionFactory.setHost("8.140.5.231");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/gsj");
connectionFactory.setUsername("gsj");
connectionFactory.setPassword("gsj");
}
public static Connection getConnection(){
try {
return connectionFactory.newConnection();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void closeConnectionAndChanel(Channel channel,Connection connection){
try {
if (channel!=null)channel.close();
if (connection!=null)connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
生产者
public class provider {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("work",true,false,false,null);
for (int i = 0; i < 10; i++) {
channel.basicPublish("","work",null,(i + "hello").getBytes());
}
RabbitMQUtil.closeConnectionAndChanel(channel,connection);
}
}
消费者1
public class Customer1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("work",true,false,false,null);
channel.basicConsume("work",true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者-1:"+new String(body));
}
});
}
}
消费者2如上
运行结果