62,614
社区成员
发帖
与我相关
我的任务
分享
public void receiveMessage(String topicName)
{
try {
Consumer consumer = new DefaultConsumer(channel)
{
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
//delivery.getEnvelope().getDeliveryTag()消息的标识,false只确认当前一个消息收到,true确认所有consumer获得的消息
channel.basicAck(envelope.getDeliveryTag(), true);
HashMap<Integer, LinkedList<Long>> message = (HashMap<Integer, LinkedList<Long>>) toObject(body);
for (Integer str : message.keySet())
{
System.out.println(" [x] Received '" + str);
}
}
};
//指定接收者,false-不自动应答
channel.basicConsume(topicName, false, consumer);
} catch (IOException e) {
e.printStackTrace();
}
}
private Object toObject (byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
@Slf4j
@Component
public class RabbitHelper {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 广播消息
* @param exchange
* @param message
*/
public void broadcast(String exchange,String message){
rabbitTemplate.convertAndSend(exchange,"",message);
}
}
消费者:
@Slf4j
@Component
public class DownCmdConsumer {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(), //注意这里不要定义队列名称,系统会随机产生
exchange = @Exchange(value = "填写交换机名称",type = ExchangeTypes.FANOUT)
)
)
public void process(String payload) {
log.info("receive:{}",payload)
}
}