使用@RabbitListener监听,但好像必须有队列的情况才能启动,但要是生产者那还没开发好,我这消费者怎么启动?
消费者会一直监听,如生产者启动就会消费消息
ConnectionFactory factory = new ConnectionFactory();
//cpolar公网地址
factory.setHost("1.tcp.cpolar.cn");
//公网地址对于的端口号
factory.setPort(24889);
//用户名和密码
factory.setUsername("admin");
factory.setPassword("123456");
Connection connection = null;
Channel channel = null;
try {
// 1.创建连接和通道
connection = factory.newConnection();
channel = connection.createChannel();
// 2.为通道声明exchange以及exchange类型
channel.exchangeDeclare("exchange", BuiltinExchangeType.FANOUT);
// 3.创建随机名字的队列
String queueName = channel.queueDeclare().getQueue();
// 4.建立exchange和队列的绑定关系
channel.queueBind(queueName, "exchange", "");
System.out.println(" **** Consumer1 keep alive ,waiting for messages, and then deal them");
// 5.通过回调生成消费者并进行监听
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
// 获取消息内容然后处理
String msg = new String(body, "UTF-8");
System.out.println("*********** Consumer1" + " get message :[" + msg + "]");
}
};
// 6.消费消息
channel.basicConsume(queueName, true, consumer);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
没有生产者,启动消费者也没有实际的消息传递过来,这么做意义不大吧