com.rabbitmq.client.Connection Java Examples
The following examples show how to use
com.rabbitmq.client.Connection.
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: NewTask.java From java-study with Apache License 2.0 | 7 votes |
public static void main(String[] argv) throws Exception { // 创建工厂类 ConnectionFactory factory = new ConnectionFactory(); //factory.setHost("localhost"); factory.setUri("amqp://guest:[email protected]:5672"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); Map map=new HashMap(); map.put("aa", 11); map.put("bb", 22); map.put("cc", 33); String message = getMessage(argv); channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); }
Example #2
Source File: AmqpForwardAttributeTest.java From james-project with Apache License 2.0 | 6 votes |
@Test public void serviceShouldPublishAttributeContentWhenAttributeInMailAndIsAList() throws Exception { mailet.init(mailetConfig); Channel channel = mock(Channel.class); Connection connection = mock(Connection.class); when(connection.createChannel()).thenReturn(channel); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); when(connectionFactory.newConnection()).thenReturn(connection); mailet.setConnectionFactory(connectionFactory); Mail mail = mock(Mail.class); when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(Optional.of(new Attribute(MAIL_ATTRIBUTE, AttributeValue.of(ImmutableList.of(AttributeValue.ofSerializable(ATTACHMENT_CONTENT)))))); BasicProperties expectedProperties = new AMQP.BasicProperties(); mailet.service(mail); ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class); verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(), eq(ATTACHMENT_CONTENT)); assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties); }
Example #3
Source File: AMPQMessageCaptureTest.java From fuchsia with Apache License 2.0 | 6 votes |
private void sendSampleAMPQMessage() throws IOException { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); final String topic = "public"; final String quote = "The force of mind is only as great as its expression; its depth only as deep as its power to expand and lose itself"; LOG.info("<eventadmin type='outbound'>"); LOG.info("\tTOPIC: {}", topic); LOG.info("\tQuote: {}", quote); LOG.info("</eventadmin>\n"); channel.basicPublish("", topic, null, quote.getBytes()); }
Example #4
Source File: RabbitMqIOTest.java From beam with Apache License 2.0 | 6 votes |
@Test(timeout = ONE_MINUTE_MS) public void testDeclareIncompatibleExchangeFails() throws Exception { RabbitMqIO.Read read = RabbitMqIO.read().withExchange("IncompatibleExchange", "direct", "unused"); try { doExchangeTest(new ExchangeTestPlan(read, 1), true); fail("Expected to have failed to declare an incompatible exchange"); } catch (Exception e) { Throwable cause = Throwables.getRootCause(e); if (cause instanceof ShutdownSignalException) { ShutdownSignalException sse = (ShutdownSignalException) cause; Method reason = sse.getReason(); if (reason instanceof com.rabbitmq.client.AMQP.Connection.Close) { com.rabbitmq.client.AMQP.Connection.Close close = (com.rabbitmq.client.AMQP.Connection.Close) reason; assertEquals("Expected failure is 530: not-allowed", 530, close.getReplyCode()); } else { fail( "Unexpected ShutdownSignalException reason. Expected Connection.Close. Got: " + reason); } } else { fail("Expected to fail with ShutdownSignalException. Instead failed with " + cause); } } }
Example #5
Source File: ConsumeAMQPTest.java From localization_nifi with Apache License 2.0 | 6 votes |
@Test public void validateSuccessfullConsumeAndTransferToSuccess() throws Exception { Map<String, List<String>> routingMap = new HashMap<>(); routingMap.put("key1", Arrays.asList("queue1", "queue2")); Map<String, String> exchangeToRoutingKeymap = new HashMap<>(); exchangeToRoutingKeymap.put("myExchange", "key1"); Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap); try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) { sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); ConsumeAMQP pubProc = new LocalConsumeAMQP(connection); TestRunner runner = TestRunners.newTestRunner(pubProc); runner.setProperty(ConsumeAMQP.HOST, "injvm"); runner.setProperty(ConsumeAMQP.QUEUE, "queue1"); runner.run(); Thread.sleep(200); final MockFlowFile successFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0); assertNotNull(successFF); } }
Example #6
Source File: MockConnectionTest.java From rabbitmq-mock with Apache License 2.0 | 6 votes |
@Test void connectionParams_are_default_ones() { Connection connection = new MockConnectionFactory().newConnection(); SoftAssertions softly = new SoftAssertions(); softly.assertThat(connection.getAddress().getHostAddress()).isEqualTo("127.0.0.1"); softly.assertThat(connection.getPort()).isEqualTo(ConnectionFactory.DEFAULT_AMQP_PORT); softly.assertThat(connection.getChannelMax()).isEqualTo(0); softly.assertThat(connection.getFrameMax()).isEqualTo(0); softly.assertThat(connection.getHeartbeat()).isEqualTo(0); softly.assertThat(connection.getClientProperties()).isEqualTo(AMQConnection.defaultClientProperties()); softly.assertThat(connection.getClientProvidedName()).isNull(); softly.assertThat(connection.getServerProperties().get("version")) .isEqualTo(LongStringHelper.asLongString(new Version(AMQP.PROTOCOL.MAJOR, AMQP.PROTOCOL.MINOR).toString())); softly.assertThat(connection.getExceptionHandler()).isExactlyInstanceOf(DefaultExceptionHandler.class); softly.assertAll(); }
Example #7
Source File: NewTask.java From rabbitmq with GNU General Public License v2.0 | 6 votes |
public static void main(String[] argv) throws java.io.IOException, Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); // �ַ���Ϣ for(int i = 0 ; i < 5; i++){ String message = "Hello World! " + i; channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); } channel.close(); connection.close(); }
Example #8
Source File: Producer.java From SpringBoot-Course with MIT License | 6 votes |
public static void main(String[] args) throws Exception { // 创建链接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("127.0.0.1"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); // 通过链接工厂创建链接 Connection connection = connectionFactory.newConnection(); // 通过链接创建通道(channel) Channel channel = connection.createChannel(); // 通过 channel 发送数据 // exchange:交换机,如果不传默认为 AMQP default String directExchangeName = "direct_exchange_name"; String directRoutingKey = "direct_routingKey"; String directMsg = "direct hello world"; channel.basicPublish(directExchangeName, directRoutingKey, null, directMsg.getBytes()); // 关闭链接 channel.close(); connection.close(); }
Example #9
Source File: ProducerExchangeConsumer_Topic.java From util4j with Apache License 2.0 | 6 votes |
public void consumer1A() 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("-->消费者1A号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString()); channel.basicAck(envelope.getDeliveryTag(), false); } }; channel.basicConsume(QUEUE_NAME1, autoAck,consumer); }
Example #10
Source File: SenderStorage.java From IGUANA with GNU Affero General Public License v3.0 | 6 votes |
protected void send(T obj) throws IOException, TimeoutException{ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitHost); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(COMMON.RP2SENDER_QUEUENAME, false, false, false, null); byte [] data = null; try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos);){ oos.writeObject(obj); oos.flush(); oos.close(); bos.close(); data = bos.toByteArray(); } if(data != null) channel.basicPublish("", COMMON.RP2SENDER_QUEUENAME, null, data); }
Example #11
Source File: AMQPObservableQueueTest.java From conductor with Apache License 2.0 | 6 votes |
private void testGetMessagesFromQueueAndDefaultConfiguration(Channel channel, Connection connection, boolean queueExists, boolean useWorkingChannel) throws IOException, TimeoutException { final Random random = new Random(); final String queueName = RandomStringUtils.randomAlphabetic(30); AMQPSettings settings = new AMQPSettings(configuration).fromURI("amqp_queue:" + queueName); List<GetResponse> queue = buildQueue(random, batchSize); channel = mockChannelForQueue(channel, useWorkingChannel, queueExists, queueName, queue); AMQPObservableQueue observableQueue = new AMQPObservableQueue( mockConnectionFactory(connection), addresses, false, settings, batchSize, pollTimeMs); assertArrayEquals(addresses, observableQueue.getAddresses()); assertEquals(AMQPConstants.AMQP_QUEUE_TYPE, observableQueue.getType()); assertEquals(AMQPConstants.AMQP_QUEUE_TYPE+":"+queueName, observableQueue.getName()); assertEquals(queueName, observableQueue.getURI()); assertEquals(batchSize, observableQueue.getBatchSize()); assertEquals(pollTimeMs, observableQueue.getPollTimeInMS()); assertEquals(queue.size(), observableQueue.size()); runObserve(channel, observableQueue, queueName, useWorkingChannel, batchSize); }
Example #12
Source File: ChannelTest.java From rabbitmq-mock with Apache License 2.0 | 6 votes |
@Test void exchangeUnbindNoWait_removes_binding() throws IOException, TimeoutException { try (Connection conn = new MockConnectionFactory().newConnection()) { try (Channel channel = conn.createChannel()) { assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull(); assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull(); assertThat(channel.queueDeclare()).isNotNull(); channel.exchangeBindNoWait("ex-to", "ex-from", "test.key", null); assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull(); channel.exchangeUnbindNoWait("ex-to", "ex-from", "test.key", null); channel.basicPublish("ex-from", "unused", null, "test message".getBytes()); GetResponse response = channel.basicGet("", true); assertThat(response).isNull(); } } }
Example #13
Source File: ProducerExchangeConsumer_Direct.java From util4j with Apache License 2.0 | 6 votes |
/** * 消费者3的队列的key和队列1的key相等 * @throws Exception */ public void consumer3() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME3, false, false, false, null); //绑定队列到交换机 channel.queueBind(QUEUE_NAME3, EXCHANGE_NAME,ROUTER_KEY_1); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) //channel.basicQos(1);//每次只从服务器取1个处理 //4、定义队列的消费者 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println("-->消费者3号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString()); channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false); }; channel.basicConsume(QUEUE_NAME3, autoAck, deliverCallback, consumerTag -> { }); }
Example #14
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void producer() throws Exception{ //1、获取连接 Connection connection = RabbitMqConnectionFactoy.getConnection(); //2、声明信道 Channel channel = connection.createChannel(); //3、声明(创建)队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //4、定义消息内容(发布多条消息) for(int i = 0 ; i < 10 ; i++){ String message = "hello rabbitmq "+i; //定义消息头 Map<String,Object> header=new HashMap<>(); header.put("i",i); BasicProperties bp=new BasicProperties.Builder().headers(header).build(); //5、发布消息 channel.basicPublish("",QUEUE_NAME,bp,message.getBytes()); System.out.println("[x] Sent'"+message+"'"); //模拟发送消息延时,便于演示多个消费者竞争接受消息 // Thread.sleep(i*10); } //6、关闭通道 channel.close(); //7、关闭连接 connection.close(); }
Example #15
Source File: RabbitQueueFactory.java From yacy_grid_mcp with GNU Lesser General Public License v2.1 | 6 votes |
private Connection getConnection() throws IOException { if (this.connection != null && this.connection.isOpen()) return this.connection; 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"); return this.connection; } catch (TimeoutException e) { throw new IOException(e.getMessage()); } }
Example #16
Source File: ProducerExchangeConsumer_Fanout.java From util4j with Apache License 2.0 | 6 votes |
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 #17
Source File: ChannelTest.java From rabbitmq-mock with Apache License 2.0 | 6 votes |
@Test void exchangeDeclare_twice_keeps_existing_bindings() throws IOException, TimeoutException { try (Connection conn = new MockConnectionFactory().newConnection()) { try (Channel channel = conn.createChannel()) { String exchangeName = "test1"; channel.exchangeDeclare(exchangeName, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchangeName, "unused"); // Declare the same exchange a second time channel.exchangeDeclare(exchangeName, "fanout"); channel.basicPublish("test1", "unused", null, "test".getBytes()); GetResponse getResponse = channel.basicGet(queueName, true); assertThat(getResponse).isNotNull(); } } }
Example #18
Source File: TestServicesUtils.java From simpleci with MIT License | 6 votes |
public static boolean testDatabase(String host, int port, String name, String user, String password) { final int tryCount = 10; for (int i = 1; i <= tryCount; i++) { try { logger.info(String.format("database: connecting to %s:%d, try %d of %d", host, port, i, tryCount)); java.sql.Connection connection = ConnectionUtils.createDataSource(host, port, name, user, password).getConnection(); connection.close(); logger.info("Connection to database established successfully"); return true; } catch (SQLException e) { logger.info("Failed to connect"); try { Thread.sleep(1000); } catch (InterruptedException e1) { logger.error("", e); } } } logger.info(String.format("Failed connect to database on %s:%d", host, port)); return false; }
Example #19
Source File: AMQPPublisherTest.java From localization_nifi with Apache License 2.0 | 6 votes |
@Test public void validateSuccessfullPublishingAndRouting() throws Exception { Map<String, List<String>> routingMap = new HashMap<>(); routingMap.put("key1", Arrays.asList("queue1", "queue2")); Map<String, String> exchangeToRoutingKeymap = new HashMap<>(); exchangeToRoutingKeymap.put("myExchange", "key1"); Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap); try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) { sender.publish("hello".getBytes(), null, "key1", "myExchange"); Thread.sleep(200); } assertNotNull(connection.createChannel().basicGet("queue1", true)); assertNotNull(connection.createChannel().basicGet("queue2", true)); connection.close(); }
Example #20
Source File: ProducerExchangeConsumer_Topic.java From util4j with Apache License 2.0 | 6 votes |
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 #21
Source File: TestClient.java From rabbitmq-cdi with MIT License | 6 votes |
public static void main(String[] args) { CountDownLatch countDown = new CountDownLatch(1); ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setHost("127.0.0.1"); try (Connection con = factory.newConnection(); Channel chn = con.createChannel()) { AtomicLong receivedMessages = new AtomicLong(); String consumerTag = chn.basicConsume("product.catalog_item.sync", true, new DefaultConsumer(chn) { @Override public void handleDelivery(String tag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { long actualCount = receivedMessages.incrementAndGet(); if (actualCount % 1000 == 0) { System.out.println("Received " + actualCount + " messages so far."); } // countDown.countDown(); } }); System.out.println(consumerTag); countDown.await(); } catch (Exception e) { e.printStackTrace(); } }
Example #22
Source File: Producer.java From SpringBoot-Course with MIT License | 6 votes |
public static void main(String[] args) throws Exception { // 创建链接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("127.0.0.1"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); // 通过链接工厂创建链接 Connection connection = connectionFactory.newConnection(); // 通过链接创建通道(channel) Channel channel = connection.createChannel(); // 通过 channel 发送数据 // exchange:交换机,如果不传默认为 AMQP default String fanoutExchangeName = "fanout_exchange_name"; String fanoutRoutingKey = ""; String fanoutMsg = "fanout hello world"; channel.basicPublish(fanoutExchangeName, fanoutRoutingKey, null, fanoutMsg.getBytes()); // 关闭链接 channel.close(); connection.close(); }
Example #23
Source File: ChannelTest.java From rabbitmq-mock with Apache License 2.0 | 6 votes |
@Test void exchangeUnbind_removes_binding() throws IOException, TimeoutException { try (Connection conn = new MockConnectionFactory().newConnection()) { try (Channel channel = conn.createChannel()) { assertThat(channel.exchangeDeclare("ex-from", BuiltinExchangeType.FANOUT)).isNotNull(); assertThat(channel.exchangeDeclare("ex-to", BuiltinExchangeType.FANOUT)).isNotNull(); assertThat(channel.queueDeclare()).isNotNull(); channel.exchangeBindNoWait("ex-to", "ex-from", "test.key", null); assertThat(channel.queueBind("", "ex-to", "queue.used")).isNotNull(); assertThat(channel.exchangeUnbind("ex-to", "ex-from", "test.key")).isNotNull(); channel.basicPublish("ex-from", "unused", null, "test message".getBytes()); GetResponse response = channel.basicGet("", true); assertThat(response).isNull(); } } }
Example #24
Source File: RabbitMqConnectionFactoy.java From util4j with Apache License 2.0 | 5 votes |
public static Connection getConnection() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); factory.setVirtualHost("/"); factory.setUsername("guest"); factory.setPassword("guest"); return factory.newConnection(); }
Example #25
Source File: ExtensionTest.java From rabbitmq-mock with Apache License 2.0 | 5 votes |
@Test void non_long_message_ttl_in_publishers_is_not_used() throws IOException, TimeoutException, InterruptedException { try (Connection conn = new MockConnectionFactory().newConnection()) { try (Channel channel = conn.createChannel()) { channel.queueDeclare("fruits", true, false, false, null); AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .expiration("test") .build(); channel.basicPublish("", "fruits", properties, "banana".getBytes()); TimeUnit.MILLISECONDS.sleep(100L); GetResponse getResponse = channel.basicGet("fruits", true); assertThat(getResponse).isNotNull(); } } }
Example #26
Source File: Send.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws Exception { Map map=new HashMap(); map.put("aa", 11); map.put("bb", 22); map.put("cc", 33); map.put("dd", 44); map.put("ff", 1); System.out.println("你好啊!"); //创建连接连接到MabbitMQ ConnectionFactory factory = new ConnectionFactory(); // 设置MabbitMQ所在主机ip或者主机名 // factory.setHost("localhost"); //factory.setHost("127.0.0.1"); factory.setUri("amqp://guest:[email protected]:5672");//获取url // 创建一个连接 Connection connection = factory.newConnection(); // 创建一个频道 Channel channel = connection.createChannel(); // 指定一个队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //发送的消息 String message = JSON.toJSONString(map); // 往队列中发出一条消息 channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); //发送 System.out.println(" [x] Sent '" + message + "'"); // 关闭频道和连接 channel.close(); connection.close(); }
Example #27
Source File: RabbitmqIT.java From uavstack with Apache License 2.0 | 5 votes |
public Connection doInstall(Connection arg) { arg = JDKProxyInvokeUtil.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[] { Connection.class }, new JDKProxyInvokeHandler<Connection>(arg, new ConnectionProxyProcessor())); return arg; }
Example #28
Source File: ConsumeAMQPTest.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testMessageAcked() throws TimeoutException, IOException { final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1")); final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1"); final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap); try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) { sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); sender.publish("world".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); ConsumeAMQP proc = new LocalConsumeAMQP(connection); TestRunner runner = TestRunners.newTestRunner(proc); runner.setProperty(ConsumeAMQP.HOST, "injvm"); runner.setProperty(ConsumeAMQP.QUEUE, "queue1"); runner.setProperty(ConsumeAMQP.AUTO_ACKNOWLEDGE, "false"); runner.run(); runner.assertTransferCount(PublishAMQP.REL_SUCCESS, 2); final MockFlowFile helloFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0); helloFF.assertContentEquals("hello"); final MockFlowFile worldFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(1); worldFF.assertContentEquals("world"); // A single cumulative ack should be used assertFalse(((TestChannel) connection.createChannel()).isAck(0)); assertTrue(((TestChannel) connection.createChannel()).isAck(1)); } }
Example #29
Source File: ConnectionManager.java From rabbitmq-cdi with MIT License | 5 votes |
Connection getConnection() throws IOException { // Retrieve the connection if it is established if (state == ConnectionState.CLOSED) { throw new IOException("Attempt to retrieve a connection from a closed connection factory"); } if (state == ConnectionState.CONNECTED) { return connection; } // Throw an exception if no established connection could not be // retrieved LOGGER.error("Unable to retrieve connection"); throw new IOException("Unable to retrieve connection"); }
Example #30
Source File: ConsumeAMQPTest.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testMessagesRejectedOnStop() throws TimeoutException, IOException { final Map<String, List<String>> routingMap = Collections.singletonMap("key1", Arrays.asList("queue1")); final Map<String, String> exchangeToRoutingKeymap = Collections.singletonMap("myExchange", "key1"); final Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap); try (AMQPPublisher sender = new AMQPPublisher(connection, mock(ComponentLog.class))) { sender.publish("hello".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); sender.publish("world".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); sender.publish("good-bye".getBytes(), MessageProperties.PERSISTENT_TEXT_PLAIN, "key1", "myExchange"); LocalConsumeAMQP proc = new LocalConsumeAMQP(connection); TestRunner runner = TestRunners.newTestRunner(proc); runner.setProperty(ConsumeAMQP.HOST, "injvm"); runner.setProperty(ConsumeAMQP.QUEUE, "queue1"); runner.setProperty(ConsumeAMQP.BATCH_SIZE, "1"); runner.run(); proc.close(); runner.assertTransferCount(PublishAMQP.REL_SUCCESS, 1); final MockFlowFile helloFF = runner.getFlowFilesForRelationship(PublishAMQP.REL_SUCCESS).get(0); helloFF.assertContentEquals("hello"); // A single cumulative ack should be used assertTrue(((TestChannel) connection.createChannel()).isAck(0)); // Messages 1 and 2 will have been delivered but on stop should be rejected. They will be rejected // cumulatively, though, so only delivery Tag 2 will be nack'ed explicitly assertTrue(((TestChannel) connection.createChannel()).isNack(2)); // Any newly delivered messages should also be immediately nack'ed. proc.getAMQPWorker().getConsumer().handleDelivery("123", new Envelope(3, false, "myExchange", "key1"), new BasicProperties(), new byte[0]); assertTrue(((TestChannel) connection.createChannel()).isNack(3)); } }