/** * Creates an instance of this worker initializing it with AMQP * {@link Connection} and creating a target {@link Channel} used by * sub-classes to interact with AMQP-based messaging system. * * @param connection instance of {@link Connection} */ public AMQPWorker(final Connection connection) { validateConnection(connection); try { this.channel = connection.createChannel(); } catch (IOException e) { logger.error("Failed to create Channel for " + connection, e); throw new IllegalStateException(e); } }
@Override public void open(Configuration config) throws Exception { ConnectionFactory factory = rmqConnectionConfig.getConnectionFactory(); try { connection = factory.newConnection(); channel = connection.createChannel(); if (channel == null) { throw new RuntimeException("None of RabbitMQ channels are available"); } setupQueue(); if (returnListener != null) { channel.addReturnListener(returnListener); } } catch (IOException e) { throw new RuntimeException("Error while creating the channel", e); } }
channel = connection.createChannel();
@Override public void open(Configuration config) throws Exception { super.open(config); ConnectionFactory factory = setupConnectionFactory(); try { connection = factory.newConnection(); channel = connection.createChannel(); if (channel == null) { throw new RuntimeException("None of RabbitMQ channels are available"); } setupQueue(); consumer = new QueueingConsumer(channel); RuntimeContext runtimeContext = getRuntimeContext(); if (runtimeContext instanceof StreamingRuntimeContext && ((StreamingRuntimeContext) runtimeContext).isCheckpointingEnabled()) { autoAck = false; // enables transaction mode channel.txSelect(); } else { autoAck = true; } LOG.debug("Starting RabbitMQ source with autoAck status: " + autoAck); channel.basicConsume(queueName, autoAck, consumer); } catch (IOException e) { throw new RuntimeException("Cannot create RMQ connection with " + queueName + " at " + rmqConnectionConfig.getHost(), e); } running = true; }
public RabbitmqProducer(MaxwellContext context) { super(context); exchangeName = context.getConfig().rabbitmqExchange; props = context.getConfig().rabbitmqMessagePersistent ? MessageProperties.MINIMAL_PERSISTENT_BASIC : null; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(context.getConfig().rabbitmqHost); factory.setPort(context.getConfig().rabbitmqPort); factory.setUsername(context.getConfig().rabbitmqUser); factory.setPassword(context.getConfig().rabbitmqPass); factory.setVirtualHost(context.getConfig().rabbitmqVirtualHost); try { this.channel = factory.newConnection().createChannel(); if(context.getConfig().rabbitmqDeclareExchange) { this.channel.exchangeDeclare(exchangeName, context.getConfig().rabbitmqExchangeType, context.getConfig().rabbitMqExchangeDurable, context.getConfig().rabbitMqExchangeAutoDelete, null); } } catch (IOException | TimeoutException e) { throw new RuntimeException(e); } }
@Test public void simpleRabbitMqTest() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMq.getContainerIpAddress()); factory.setPort(rabbitMq.getMappedPort(RABBITMQ_PORT)); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(RABBIQMQ_TEST_EXCHANGE, "direct", true); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY); // Set up a consumer on the queue final boolean[] messageWasReceived = new boolean[1]; channel.basicConsume(queueName, false, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { messageWasReceived[0] = Arrays.equals(body, RABBITMQ_TEST_MESSAGE.getBytes()); } }); // post a message channel.basicPublish(RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY, null, RABBITMQ_TEST_MESSAGE.getBytes()); // check the message was received assertTrue("The message was received", Unreliables.retryUntilSuccess(5, TimeUnit.SECONDS, () -> { if (!messageWasReceived[0]) { throw new IllegalStateException("Message not received yet"); } return true; })); }
final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey);
private void connect() throws IOException { Map<String, Object> arguments = new HashMap<>(); arguments.put("x-queue-mode", "lazy"); // we want to minimize memory usage; see http://www.rabbitmq.com/lazy-queues.html boolean lazys = lazy.get(); try { RabbitQueueFactory.this.channel.queueDeclare(this.queueName, true, false, false, lazys ? arguments : null); } catch (AlreadyClosedException e) { lazys = !lazys; try { channel = connection.createChannel(); // may happen if a queue was previously not declared "lazy". So we try non-lazy queue setting now. RabbitQueueFactory.this.channel.queueDeclare(this.queueName, true, false, false, lazys ? arguments : null); // if this is successfull, set the new lazy value lazy.set(lazys); } catch (AlreadyClosedException ee) { throw new IOException(ee.getMessage()); } } }
public void construct() { try { eventChan = conn.createChannel(); eventChan.queueDeclare(queueName, false, false, true, queueArguments()); eventChan.basicConsume(queueName, true, this); } catch (IOException e) { throw new CloudRuntimeException(e); } }
pool = new ArrayBlockingQueue<Channel>(size); for (int i = 0; i < size; i++) { Channel chan = connection.createChannel(); pool.add(chan); chan.addReturnListener(new ReturnListener() {
private void init() throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setAutomaticRecoveryEnabled(true); factory.setHost(this.server); if (this.port > 0) factory.setPort(this.port); if (this.username != null && this.username.length() > 0) factory.setUsername(this.username); if (this.password != null && this.password.length() > 0) factory.setPassword(this.password); try { this.connection = factory.newConnection(); //Map<String, Object> map = this.connection.getServerProperties(); if (!this.connection.isOpen()) throw new IOException("no connection"); this.channel = connection.createChannel(); if (!this.channel.isOpen()) throw new IOException("no channel"); this.queues = new ConcurrentHashMap<>(); } catch (TimeoutException e) { throw new IOException(e.getMessage()); } }
public void construct() { try { nrouteChan = conn.createChannel(); nrouteChan.queueDeclare(nrouteName, false, false, true, null); nrouteChan.queueBind(nrouteName, BusExchange.NO_ROUTE.toString(), ""); nrouteChan.basicConsume(nrouteName, true, this); } catch (IOException e) { throw new CloudRuntimeException(e); } }
public static void main(String[] args) { try { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setHost("60.205.191.82"); factory.setPort(5672); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); // channel.qu channel.queueDeclare("hello", false, false, false, null); String message = "Hello World!"; channel.basicPublish("", "hello", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); conn.close(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } }
void init() { try { ConnectionFactory connFactory = new ConnectionFactory(); List<Address> addresses = CollectionUtils.transformToList(bus.getServerIps(), new Function<Address, String>() { @Override public Address call(String arg) { return Address.parseAddress(arg); } }); conn = connFactory.newConnection(addresses.toArray(new Address[]{})); chan = conn.createChannel(); String name = MessageTracker.class.getName(); chan.queueDeclare(name, true, false, true, null); chan.basicConsume(name, true, this); chan.queueBind(name, BusExchange.P2P.toString(), "#"); chan.queueBind(name, BusExchange.BROADCAST.toString(), "#"); } catch (Exception e) { throw new CloudRuntimeException(e); } }
@Bean public CachingConnectionFactory cf() throws Exception { ConnectionFactory cf = mock(ConnectionFactory.class); cf.setHost("localhost"); cf = spy(cf); willAnswer(i -> { this.connection = mock(Connection.class); willAnswer(ii -> { this.channel = mock(Channel.class); given(this.channel.isOpen()).willReturn(true); return this.channel; }).given(this.connection).createChannel(); return this.connection; }).given(cf).newConnection((ExecutorService) isNull(), anyString()); cf.setAutomaticRecoveryEnabled(false); CachingConnectionFactory ccf = new CachingConnectionFactory(cf); ccf.setSimplePublisherConfirms(true); return ccf; }
private void testNackOrRequeue(boolean requeue) throws IOException, TimeoutException { Channel channel = mock(Channel.class); willReturn(true).given(channel).isOpen(); Envelope envelope = new Envelope(123L, false, "ex", "rk"); BasicProperties props = new BasicProperties.Builder().build(); GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0); willReturn(getResponse).given(channel).basicGet("foo", false); Connection connection = mock(Connection.class); willReturn(true).given(connection).isOpen(); willReturn(channel).given(connection).createChannel(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString()); CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory); AmqpMessageSource source = new AmqpMessageSource(ccf, "foo"); Message<?> received = source.receive(); verify(connection).createChannel(); StaticMessageHeaderAccessor.getAcknowledgmentCallback(received) .acknowledge(requeue ? Status.REQUEUE : Status.REJECT); verify(channel).basicReject(123L, requeue); verify(connection).createChannel(); ccf.destroy(); verify(channel).close(); verify(connection).close(30000); }
Connection connection = mock(Connection.class); willReturn(true).given(connection).isOpen(); willReturn(channel).given(connection).createChannel(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString()); verify(connection, times(2)).createChannel(); StaticMessageHeaderAccessor.getAcknowledgmentCallback(received) .acknowledge(Status.ACCEPT); verify(channel).basicAck(123L, false); Channel cached = conn.createChannel(false); // should have been "closed" verify(connection, times(2)).createChannel(); notCached.close(); cached.close();
private void open() throws IOException, TimeoutException { connection = RabbitMQUtil.createConnection(brokerAddresses, brokerUsername, brokerPassword); if (blockedListener != null) { connection.addBlockedListener(blockedListener); } channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct"); log.info("[rabbit.producer] connection established."); }
@Test public void test(ConnectionFactory connectionFactory) throws Exception { Connection conn = connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close(); conn.close(); }
@Test public void test(ConnectionFactory cf) throws Exception { assertSame(cf, this.connectionFactory); Connection conn = this.connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close(); conn.close(); }