private static final String EXCHANGE_NAME = "direct_logs"; private static final String DELAY_EXCHANGE_NAME = "delay_exchange"; private static final String ROUTING_KEY = "error";
// 生产者 public static void main(String[] args) { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("10.202.72.206"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME,"direct"); String msg = "talk is cheap ,show me the code "; for(int i = 0;i <10;i++){ channel.basicPublish(EXCHANGE_NAME,ROUTING_KEY,null,msg.getBytes()); } System.out.println(" [x] Sent '" + ROUTING_KEY + "':'" + msg + "'"); }catch (Exception e){ System.out.println("something wrong"); e.printStackTrace(); } }
private static final String EXCHANGE_NAME = "direct_logs"; private static final String DELAY_EXCHANGE_NAME = "delay_exchange"; private static final String ROUTING_KEY = "error"; private static final String QUEUE_NAME = "myqueue"; //消费者 public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("10.202.72.206"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String msg = new String(body, "utf-8"); System.out.println("[1] Recv msg:" + msg); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println("[1] done "); channel.basicAck(envelope.getDeliveryTag(), false); } } }; //自动应答 false boolean autoAck=false; channel.basicConsume(queueName,autoAck, consumer); }