生产者
package com.example.demo.produce; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class MyProcuder { public static void main(String[] args) throws Exception { //1 创建一个ConnectionFactory,并进行配置 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("39.106.128.***"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); //2 通过连接工厂创建连接 Connection connection = connectionFactory.newConnection(); //3 通过connection创建一个channel Channel channel = connection.createChannel(); //4 通过channel发送数据 String exchange = "exchange001"; String routingKey = "routingkey001"; String body = "this is a message"; channel.basicPublish(exchange, routingKey, null, body.getBytes()); //5 关闭相关连接 channel.close(); connection.close(); } }
消费者
package com.example.demo.constumer; import com.rabbitmq.client.*; public class Consumer { public static void main(String[] args) throws Exception{ //1 创建一个ConnectionFactory,并进行配置 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("39.106.128.***"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); //2 通过连接工厂创建连接 Connection connection = connectionFactory.newConnection(); //3 通过connection创建一个channel Channel channel = connection.createChannel(); //4 声明(创建)一个队列 String queue = "queue001"; String exchangeName = "exchange001"; String routingKey = "routingkey001"; //是否持久化 boolean durable = true; boolean exclusive = false; boolean autoDelete = false; channel.exchangeDeclare(exchangeName, "topic", true, false, null); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchangeName, routingKey); //5 创建消费者 // Step06: let the consumer consume the queue channel.basicConsume(queue, true, new MyConsumer(channel)); } }
自定义消费者
package com.example.demo.constumer; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; public class MyConsumer extends DefaultConsumer { public MyConsumer(Channel channel) { super(channel); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) { String message = null; try { message = new String(body, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } System.out.println("消费者接收到的消息:" + message); } }
来源:oschina
链接:https://my.oschina.net/u/4253180/blog/3163588