mq的基本规则这里就不阐述了,请移步到
mq简介
mq服务安装请自行百度
topic 模式和 Direct 都是根据 routingKey 进行发送到对应列队所以发送时候不需要指定queueName
代码如下
创建mqfactory
public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("10.10.25.118");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
return connectionFactory.newConnection();
}
创建发送端
//交换机名称
private static final String EXCHANGE_NAME = "test_exchange_topic";
private static final String ROW_KEY = "row.key"
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
String message = "订阅消息123456";
channel.basicPublish(EXCHANGE_NAME, ROW_KEY, null, message.getBytes());
System.out.println("生产者 send :" + message);
channel.close();
connection.close();
}
接收者,需要声明exchange和queue和routingKey的bind关系 第一次启动后。mq管理后台就可以查询到
public static void main(String[] args) throws IOException {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROW_KEY);
//同一时刻服务器只会发一条数据给消费者
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body)
throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String message = new String(body, "UTF-8");
System.out.println("收到消息:" + message);
//手动签收
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
//第二个参数,是否需要手动应答
channel.basicConsume(QUEUE_NAME, false, consumer);
}