Java Code Examples for com.rabbitmq.client.Channel#queueBind()

The following examples show how to use com.rabbitmq.client.Channel#queueBind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1B() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME,"test.a");//只收到基数
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1B号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example 2
Source File: ProducerExchangeConsumer_Fanout.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer2() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME2, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME,"");
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次只从服务器取1个处理
       //4、定义队列的消费者
       DeliverCallback deliverCallback = (consumerTag, delivery) -> {
           String message = new String(delivery.getBody(), "UTF-8");
           System.out.println("-->消费者2号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString());
           channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false);
       };
       channel.basicConsume(QUEUE_NAME2, autoAck, deliverCallback, consumerTag -> { });
}
 
Example 3
Source File: ProducerExchangeConsumer_Fanout.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer1() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME1, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "");
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次处理1个
       //4、定义队列的消费者
       //定义消费者
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
               channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(QUEUE_NAME1, autoAck,consumer);
}
 
Example 4
Source File: MessageSubscriberFactory.java    From Insights with Apache License 2.0 6 votes vote down vote up
public void registerSubscriber(String routingKey, final EngineSubscriberResponseHandler responseHandler) throws Exception {
	Channel channel = connection.createChannel();
	String queueName = routingKey.replace(".", "_");
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, MessageConstants.EXCHANGE_NAME, routingKey);
	channel.basicQos(ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount());
	responseHandler.setChannel(channel);
	log.debug("prefetchCount "+ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount() );
	Consumer consumer = new DefaultConsumer(channel) {
		@Override
		public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
				byte[] body) throws IOException {
			responseHandler.handleDelivery(consumerTag, envelope, properties, body);
		}
	};
	channel.basicConsume(queueName, false, routingKey, consumer);
}
 
Example 5
Source File: QueueConfig.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Bean
public RabbitQueueOperation deadLetterQueueManager(Connection rabbitConnection) throws IOException {
    String name = rabbitProperties.getJobDlQueue();
    String exchange = rabbitProperties.getJobDlExchange();

    RabbitQueueOperation manager = new RabbitQueueOperation(rabbitConnection, 1, name);
    manager.declare(true);

    Map<String, Object> props = new HashMap<>(0);

    Channel channel = manager.getChannel();
    channel.exchangeDeclare(exchange, BuiltinExchangeType.DIRECT, true, false, props);
    channel.queueBind(manager.getQueueName(), exchange, JobDlRoutingKey);

    return manager;
}
 
Example 6
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void consumer2() throws Exception {
	//1、获取连接
       Connection connection =RabbitMqConnectionFactoy.getConnection();
       //2、声明通道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(QUEUE_NAME2, false, false, false, null);
       //绑定队列到交换机
       channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME,"test.#");//基数偶数都接收
       //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
       //channel.basicQos(1);//每次只从服务器取1个处理
       //4、定义队列的消费者
       DeliverCallback deliverCallback = (consumerTag, delivery) -> {
           String message = new String(delivery.getBody(), "UTF-8");
           System.out.println("-->消费者2号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString());
           channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false);
       };
       channel.basicConsume(QUEUE_NAME2, autoAck, deliverCallback, consumerTag -> { });
}
 
Example 7
Source File: Consumer4DirectExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {


        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.ip);
        connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        //4 声明
        String exchangeName = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        String routingKey = "test.direct";

        //表示声明了一个交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        //表示声明了一个队列
        channel.queueDeclare(queueName, false, false, false, null);
        //建立一个绑定关系:
        channel.queueBind(queueName, exchangeName, routingKey);

        //durable 是否持久化消息
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数:队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
        //循环获取消息  
        while (true) {
            //获取消息,如果没有消息,这一步将会一直阻塞  
            Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("收到消息:" + msg);
        }
    }
 
Example 8
Source File: Consumer4TopicExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	
       ConnectionFactory connectionFactory = new ConnectionFactory() ;

       connectionFactory.setHost(Constant.ip);
       connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
       connectionFactory.setAutomaticRecoveryEnabled(true);
       connectionFactory.setNetworkRecoveryInterval(3000);
       Connection connection = connectionFactory.newConnection();
       
       Channel channel = connection.createChannel();  
	//4 声明
	String exchangeName = "test_topic_exchange";
	String exchangeType = "topic";
	String queueName = "test_topic_queue";
	String routingKey = "user.#";
	//String routingKey = "user.*";
	// 1 声明交换机 
	channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
	// 2 声明队列
	channel.queueDeclare(queueName, false, false, false, null);
	// 3 建立交换机和队列的绑定关系:
	channel.queueBind(queueName, exchangeName, routingKey);
	
       //durable 是否持久化消息
       QueueingConsumer consumer = new QueueingConsumer(channel);
       //参数:队列名称、是否自动ACK、Consumer
       channel.basicConsume(queueName, true, consumer);  
       //循环获取消息  
       while(true){  
           //获取消息,如果没有消息,这一步将会一直阻塞  
           Delivery delivery = consumer.nextDelivery();  
           String msg = new String(delivery.getBody());
           System.out.println("收到消息:" + msg);
       } 
}
 
Example 9
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {


        //1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost(Constant.ip);
		connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        //2 获取C	onnection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";
        String queueName = "test_confirm_queue";

        //4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, queueingConsumer);

        while (true) {
            Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());

            System.err.println("消费端: " + msg);
        }


    }
 
Example 10
Source File: QueueConfig.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Bean
public RabbitQueueOperation loggingQueueManager(Connection rabbitConnection) throws IOException {
    String name = rabbitProperties.getLoggingQueue();
    String exchange = rabbitProperties.getLoggingExchange();

    RabbitQueueOperation manager = new RabbitQueueOperation(rabbitConnection, 10, name);
    manager.declare(false);

    Channel channel = manager.getChannel();
    channel.exchangeDeclare(exchange, BuiltinExchangeType.FANOUT);
    channel.queueBind(manager.getQueueName(), exchange, StringHelper.EMPTY);

    return manager;
}
 
Example 11
Source File: Consumer4FanoutExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
       ConnectionFactory connectionFactory = new ConnectionFactory() ;
       connectionFactory.setHost(Constant.ip);
       connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
       connectionFactory.setAutomaticRecoveryEnabled(true);
       connectionFactory.setNetworkRecoveryInterval(3000);
       Connection connection = connectionFactory.newConnection();
       
       Channel channel = connection.createChannel();  
	//4 声明
	String exchangeName = "test_fanout_exchange";
	String exchangeType = "fanout";
	String queueName = "test_fanout_queue";
	String routingKey = "";	//不设置路由键
	channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
	channel.queueDeclare(queueName, false, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
       //durable 是否持久化消息
       QueueingConsumer consumer = new QueueingConsumer(channel);
       //参数:队列名称、是否自动ACK、Consumer
       channel.basicConsume(queueName, true, consumer); 
       //循环获取消息  
       while(true){  
           //获取消息,如果没有消息,这一步将会一直阻塞  
           Delivery delivery = consumer.nextDelivery();  
           String msg = new String(delivery.getBody());
           System.out.println("收到消息:" + msg);
       } 
}
 
Example 12
Source File: ChannelPoolListener.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void initialize(final Channel channel) throws IOException {
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    channel.exchangeDeclare("order", BuiltinExchangeType.DIRECT, true);
    channel.queueDeclare("registered-order", true, false, false, null);
    channel.queueBind("registered-order", "order", "registered-order");
}
 
Example 13
Source File: ChannelPoolListener.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void initialize(final Channel channel) throws IOException {
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    channel.exchangeDeclare("order", BuiltinExchangeType.DIRECT, true);
    channel.queueDeclare("registered-order", true, false, false, null);
    channel.queueBind("registered-order", "order", "registered-order");
}
 
Example 14
Source File: RabbitEc2LiveTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
protected void doTest(Location loc) throws Exception {
    RabbitBroker rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class));
    rabbit.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(rabbit, RabbitBroker.SERVICE_UP, true);

    byte[] content = "MessageBody".getBytes(Charsets.UTF_8);
    String queue = "queueName";
    Channel producer = null;
    Channel consumer = null;
    try {
        producer = getAmqpChannel(rabbit);
        consumer = getAmqpChannel(rabbit);

        producer.queueDeclare(queue, true, false, false, Maps.<String,Object>newHashMap());
        producer.queueBind(queue, AmqpExchange.DIRECT, queue);
        producer.basicPublish(AmqpExchange.DIRECT, queue, null, content);
        
        QueueingConsumer queueConsumer = new QueueingConsumer(consumer);
        consumer.basicConsume(queue, true, queueConsumer);
    
        QueueingConsumer.Delivery delivery = queueConsumer.nextDelivery();
        assertEquals(delivery.getBody(), content);
    } finally {
        if (producer != null) producer.close();
        if (consumer != null) consumer.close();
    }
}
 
Example 15
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost(Constant.ip);
		connectionFactory.setPort(Constant.port);
		connectionFactory.setVirtualHost("/");
		
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
		
		// 这就是一个普通的交换机 和 队列 以及路由
		String exchangeName = "test_dlx_exchange";
		String queueName = "test_dlx_queue";
		String routingKey = "dlx.#";
		
		channel.exchangeDeclare(exchangeName, "topic", true, false, null);

		Map<String, Object> arguments = new HashMap<>();
		arguments.put("x-dead-letter-exchange", "dlx.exchange");
		//这个agruments属性,要设置到声明队列上
		channel.queueDeclare(queueName, true, false, false, arguments);
		channel.queueBind(queueName, exchangeName, routingKey);
		
		//要进行死信队列的声明:
		channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
		channel.queueDeclare("dlx.queue", true, false, false, null);
		channel.queueBind("dlx.queue", "dlx.exchange", "#");
		
		channel.basicConsume(queueName, true, new MyConsumer(channel));
		
		
	}
 
Example 16
Source File: Consumer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	Connection connection = connectionFactory.newConnection();
	Channel channel = connection.createChannel();
	
	
	String exchangeName = "test_qos_exchange";
	String queueName = "test_qos_queue";
	String routingKey = "qos.#";
	
	channel.exchangeDeclare(exchangeName, "topic", true, false, null);
	channel.queueDeclare(queueName, true, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
	/*
	 * prefetchSize:消息限制大小,一般为0,不做限制。
	 * prefetchCount:一次处理消息的个数,一般设置为1
	 * global:一般为false。true,在channel级别做限制;false,在consumer级别做限制
	 */
	channel.basicQos(0, 1, false);

	// 限流方式  第一件事就是 autoAck设置为 false
	channel.basicConsume(queueName, false, new MyConsumer(channel));
	
	
}
 
Example 17
Source File: DefaultChannelFactory.java    From rxrabbit with MIT License 4 votes vote down vote up
ConsumeChannelImpl( Channel delegate, String exchange, String routingKey,int hashCode, ChannelType channelType, DefaultChannelFactory factory) throws IOException {
    super(delegate, hashCode, channelType, factory);
    AMQP.Queue.DeclareOk q = delegate.queueDeclare();
    delegate.queueBind(q.getQueue(), exchange, routingKey);
    this.queue = q.getQueue();
}
 
Example 18
Source File: RabbitMQMessagingService.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
private void ensureQueueExists(final Channel channel,final String queueName) throws IOException {
    // ensure we have the queue created on the broker
    AMQP.Queue.DeclareOk result = channel.queueDeclare(queueName, true, false, false, null);
    // and bound to the exchange
    channel.queueBind(queueName,exchangeName,queueName);
}
 
Example 19
Source File: QueueService.java    From cukes with Apache License 2.0 4 votes vote down vote up
@SneakyThrows(IOException.class)
public void declareQueue(String queueName, String exchange, String routingKey) {
    Channel channel = connectionService.getChannel();
    channel.queueDeclare(queueName, false, true,true, null);
    channel.queueBind(queueName, exchange, routingKey);
}
 
Example 20
Source File: RabbitMQTestRunner.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
void runPullTest() throws Exception {

        final String message = "hello rabbit mq";

        // producer side
        final Connection producerConnection = connectionFactory.newConnection();
        final Channel producerChannel = producerConnection.createChannel();

        producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
        producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null);
        producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
        producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false, false, builder.appId("test").build(), message.getBytes());

        producerChannel.close();
        producerConnection.close();

        //comsumer side
        final Connection consumerConnection = connectionFactory.newConnection();
        final Channel consumerChannel = consumerConnection.createChannel();
        final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":" + consumerConnection.getPort();

        TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel);
        Assert.assertEquals(message, messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true));

        consumerChannel.close();
        consumerConnection.close();

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        // Wait till all traces are recorded (consumer traces are recorded from another thread)
        awaitAndVerifyTraceCount(verifier, 5, 5000L);

        verifier.printCache();
        // verify producer traces
        Class<?> producerChannelClass = producerChannel.getClass();
        Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class, String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
        ExpectedTrace channelBasicPublishTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
                channelBasicPublish, // method
                null, // rpc
                remoteAddress, // endPoint
                "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
                Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
                Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
        ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(
                RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
                "RabbitMQ Consumer Invocation", // method
                "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
                null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
                remoteAddress, // remoteAddress
                Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
        Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
        Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand", AMQCommand.class);
        ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
                handleCompleteInboundCommand); // method
        ExpectedTrace[] producerTraces = {channelBasicPublishTrace};
        ExpectedTrace[] consumerTraces = {rabbitMqConsumerInvocationTrace, handleCompleteInboundCommandTrace};
        verifier.verifyDiscreteTrace(producerTraces);
        verifier.verifyDiscreteTrace(consumerTraces);

        // verify consumer traces
        Class<?> consumerChannelClass = consumerChannel.getClass();
        Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class);
        ExpectedTrace channelBasicGetTrace = Expectations.event(
                RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
                channelBasicGet);
        Class<?> propagationMarkerClass = PropagationMarker.class;
        Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
        ExpectedTrace markTrace = Expectations.event(
                ServiceType.INTERNAL_METHOD.getName(),
                propagationMarkerMark);
        verifier.verifyDiscreteTrace(
                channelBasicGetTrace,
                markTrace);
        verifier.verifyTraceCount(0);
    }