这个入门程序就是为了体验RabbitMq消息传递的过程
生产者代码:
引入依赖:
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.26.0</version> </dependency>
java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ProducerDemon {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory =new ConnectionFactory();
connectionFactory.setUsername("study");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("study");
connectionFactory.setPassword("123456");
connectionFactory.setHost("192.168.46.107");
//创建连接 Connection
Connection connection = connectionFactory.newConnection();
//创建 信道:Channel
Channel channel = connection.createChannel();
//声明交换机,这里使用默认的交换机
//声明队列
channel.queueDeclare("study",false,false,false,null);
//发送消息
String msg="你好";
channel.basicPublish("","study",null,msg.getBytes());
System.out.println("消息发送成功");
channel.close();
connection.close();
}
}
消费者代码:
java
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConsumerDemon {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory=new ConnectionFactory();
connectionFactory.setHost("192.168.46.107");
connectionFactory.setUsername("study");
connectionFactory.setPassword("123456");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("study");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("接收到消息:"+new String(body));
}
};
channel.basicConsume("study", true, consumer);
}
}
上述代码可以直接赋值,改一下其中的参数即可.