生产者
public class PublisherDemo { @Test public void testSendMessage() throws IOException, TimeoutException { //1.创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.138.100"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itheima"); factory.setPassword("itheima"); Connection connection = factory.newConnection(); //2.创建通道 Channel channel = connection.createChannel(); //3.声明交换机与队列 /** * @param queue 队列名称 * @param durable 是否持久化 * @param exclusive 是否排它 * @param autoDelete 是否自动删除 * @param arguments 队列其他参数 * @return a declaration-confirm method to indicate the queue was successfully declared * @throws IOException if an error is encountered */ channel.queueDeclare("simple.queue", true, false, false, null); //4.发送消息 /** * exchange 交换机,默认的交换机是"" * routingKey 路由Key * props 消费其他参数 * body 消息内容 */ channel.basicPublish("", "simple.queue", null, "Hello,RabbitMQ!! Two".getBytes()); //5.释放资源 channel.close(); connection.close(); } }
消费者
public class ConsumerDemo { public static void main(String[] args) throws IOException, TimeoutException { //1.创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.138.100"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("itheima"); factory.setPassword("itheima"); Connection connection = factory.newConnection(); //2.创建通道 Channel channel = connection.createChannel(); //3.声明交换机与队列 /** * 如果队列已经存在,则不会重复创建 */ channel.queueDeclare("simple.queue", true, false, false, null); //4.消费消息 channel.basicConsume("simple.queue", new DefaultConsumer(channel){ @Override /** * consumerTag 消息标签 * Envelope envelope 封装了消息的对象(没有内容) * AMQP.BasicProperties properties 其他数据 * byte[] body 消息内容 */ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println(consumerTag); System.out.println(envelope.getDeliveryTag()); System.out.println(envelope.getExchange()); System.out.println(envelope.getRoutingKey()); System.out.println("消息内容:" + new String(body)); } }); //5.卡住 System.in.read(); } }