赞
踩
Exchange和Exchange、Queue之间的连接关系
public static final String EXCHANGE_NAME = "test_exchange_message"; public static final String ROUTING_KEY = "routingkey.message"; public static void main(String[] args) throws IOException, TimeoutException { // 获取连接 Connection connection = ConnectionsUtils.getConnection(); // 创建信道 Channel channel = connection.createChannel(); // 发送消息 String message = "test message for exchange_message"; Map headers = new HashMap(); headers.put("my1","111"); headers.put("my2","222"); AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .deliveryMode(2) // 2代表持久化消息,1:非持久化 .expiration("6000") //过期时间 .contentEncoding("utf-8")// 编码格式 .headers(headers) .build(); channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, properties, message.getBytes()); System.out.println("发送成功:" + message); channel.close(); connection.close(); }
消费者
public static final String EXCHANGE_NAME = "test_exchange_message"; public static final String EXCHANGE_TYPE = "direct"; public static final String ROUTING_KEY = "routingkey.message"; public static final String QUEUE_NAME = "test_queue_message"; public static void main(String[] args) throws IOException, TimeoutException { // 获取连接 Connection connection = ConnectionsUtils.getConnection(); // 创建信道 Channel channel = connection.createChannel(); // 声明交换机 channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, false ,null); // 声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 绑定 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY); // 创建消费者进行监听获取消息 DefaultConsumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("接收消息message: " + new String(body)); Map map = properties.getHeaders(); System.out.println(map.get("my1")); System.out.println(map.get("my2")); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
启动消费者监听,进行消息发送,会在消费者控制台接受到消息和消息附带参数值
虚拟主机
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。