Java Code Examples for com.rabbitmq.client.ConnectionFactory#setUri()
The following examples show how to use
com.rabbitmq.client.ConnectionFactory#setUri() .
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: Publisher.java From rabbitmq-tutorial with MIT License | 8 votes |
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://guest:guest@localhost"); factory.setConnectionTimeout(300000); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("my-queue", true, false, false, null); int count = 0; while (count < 5000) { String message = "Message number " + count; channel.basicPublish("", "my-queue", null, message.getBytes()); count++; System.out.println("Published message: " + message); Thread.sleep(5000); } }
Example 2
Source File: RabbitMQClientReconnectTest.java From vertx-rabbitmq-client with Apache License 2.0 | 7 votes |
@Override public RabbitMQOptions config() throws Exception { RabbitMQOptions cfg = super.config(); String username; String password; if (cfg.getUri() != null) { ConnectionFactory cf = new ConnectionFactory(); cf.setUri(cfg.getUri()); username = cf.getUsername(); password = cf.getPassword(); } else { username = "guest"; password = "guest"; } String uri = "amqp://" + username + ":" + password + "@localhost:" + PROXY_PORT; return new RabbitMQOptions() .setUri(uri) .setConnectionRetries(connectionRetries) .setConnectionRetryDelay(connectionRetryDelay); }
Example 3
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 4
Source File: AmqpWriter.java From kieker with Apache License 2.0 | 6 votes |
private Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException, IOException, TimeoutException { final ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri(this.uri); connectionFactory.setRequestedHeartbeat(this.heartbeat); // Use only daemon threads for connections. Otherwise, all connections would have to be explicitly // closed for the JVM to terminate. connectionFactory.setThreadFactory(new DaemonThreadFactory()); return connectionFactory.newConnection(); }
Example 5
Source File: RabbitEc2LiveTest.java From brooklyn-library with Apache License 2.0 | 6 votes |
private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception { String uri = rabbit.getAttribute(MessageBroker.BROKER_URL); LOG.warn("connecting to rabbit {}", uri); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(uri); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); return channel; }
Example 6
Source File: AmqpForwardAttribute.java From james-project with Apache License 2.0 | 5 votes |
@Override public void init() throws MailetException { String uri = getInitParameter(URI_PARAMETER_NAME); if (Strings.isNullOrEmpty(uri)) { throw new MailetException("No value for " + URI_PARAMETER_NAME + " parameter was provided."); } exchange = getInitParameter(EXCHANGE_PARAMETER_NAME); if (Strings.isNullOrEmpty(exchange)) { throw new MailetException("No value for " + EXCHANGE_PARAMETER_NAME + " parameter was provided."); } routingKey = getInitParameter(ROUTING_KEY_PARAMETER_NAME, ROUTING_KEY_DEFAULT_VALUE); String rawAttribute = getInitParameter(ATTRIBUTE_PARAMETER_NAME); if (Strings.isNullOrEmpty(rawAttribute)) { throw new MailetException("No value for " + ATTRIBUTE_PARAMETER_NAME + " parameter was provided."); } attribute = AttributeName.of(rawAttribute); connectionFactory = new ConnectionFactory(); try { connectionFactory.setUri(uri); } catch (Exception e) { throw new MailetException("Invalid " + URI_PARAMETER_NAME + " parameter was provided: " + uri, e); } }
Example 7
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 8
Source File: ChunkingAmqpReader.java From kieker with Apache License 2.0 | 5 votes |
private Connection createConnection() throws IOException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException { final ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri(this.uri); connectionFactory.setRequestedHeartbeat(this.heartbeat); return connectionFactory.newConnection(); }
Example 9
Source File: Recv.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); // 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); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); // 创建队列消费者 QueueingConsumer consumer = new QueueingConsumer(channel); // 指定消费队列 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { //消费者程序运行开着 如果生产者新增了数据会自动获取 Thread.sleep(500); List aa=new ArrayList(); // nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法) QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); aa.add(message); System.out.println("你好吗!"+" [x] Received '" + message + "'"+aa); } }
Example 10
Source File: RabbitMQConnectionFactory.java From james-project with Apache License 2.0 | 5 votes |
private ConnectionFactory from(RabbitMQConfiguration rabbitMQConfiguration) { try { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri(rabbitMQConfiguration.getUri()); connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeoutInMs()); connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeoutInMs()); connectionFactory.setChannelRpcTimeout(rabbitMQConfiguration.getChannelRpcTimeoutInMs()); connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeoutInMs()); connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryIntervalInMs()); return connectionFactory; } catch (Exception e) { throw new RuntimeException(e); } }
Example 11
Source File: QueueConfig.java From flow-platform-x with Apache License 2.0 | 5 votes |
@Bean public Connection rabbitConnection(ThreadPoolTaskExecutor rabbitConsumerExecutor) throws Throwable { log.info("Rabbit URI: {}", rabbitProperties.getUri()); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(rabbitProperties.getUri()); factory.setRequestedHeartbeat(1800); return factory.newConnection(rabbitConsumerExecutor.getThreadPoolExecutor()); }
Example 12
Source File: ConnectionBasedRabbitConnectionFactoryFactory.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Override public ConnectionFactory createConnectionFactory(final Connection connection, final ExceptionHandler exceptionHandler) { checkNotNull(connection, "Connection"); checkNotNull(exceptionHandler, "Exception Handler"); try { final ConnectionFactory connectionFactory = new CustomConnectionFactory(); if (SECURE_AMQP_SCHEME.equalsIgnoreCase(connection.getProtocol())) { if (connection.isValidateCertificates()) { final SSLContextCreator sslContextCreator = SSLContextCreator.fromConnection(connection, null); connectionFactory.useSslProtocol(sslContextCreator.withoutClientCertificate()); } else { // attention: this accepts all certificates whether they are valid or not connectionFactory.useSslProtocol(); } } connectionFactory.setUri(connection.getUri()); // this makes no difference as the used newmotion client always sets the AutomaticRecoveryEnabled to false: connectionFactory.setAutomaticRecoveryEnabled(connection.isFailoverEnabled()); connectionFactory.setExceptionHandler(exceptionHandler); configureConnectionFactory(connectionFactory, connection.getSpecificConfig()); return connectionFactory; } catch (final NoSuchAlgorithmException | KeyManagementException | URISyntaxException e) { LOGGER.warn(e.getMessage()); throw new IllegalStateException("Failed to create RabbitMQ connection factory.", e); } }
Example 13
Source File: RabbitReader.java From bluima with Apache License 2.0 | 5 votes |
@Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); try { // setup connection ConnectionFactory factory = new ConnectionFactory(); if (amqpUri == null) { factory.setHost("localhost"); } else { factory.setUri(amqpUri); } Connection connection = factory.newConnection(); LOG.info(" [RabbitReader] connected to Rabbit"); // receiving // setup channels receiveChannel = connection.createChannel(); receiveChannel.queueDeclare(queue, DURABLE, false, false, null); receiveChannel.basicQos(1); // max 1 msg at a time to each slave // receiving consumer = new QueueingConsumer(receiveChannel); receiveChannel.basicConsume(queue, false, consumer); LOG.debug(" [RabbitReader] Waiting for messages..."); } catch (Exception e) { throw new ResourceInitializationException(e); } }
Example 14
Source File: RabbitIntegrationTest.java From brooklyn-library with Apache License 2.0 | 5 votes |
private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception { String uri = rabbit.getAttribute(MessageBroker.BROKER_URL); log.warn("connecting to rabbit {}", uri); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(uri); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); return channel; }
Example 15
Source File: RabbitMQClientReconnectTest.java From vertx-rabbitmq-client with Apache License 2.0 | 4 votes |
private void startProxy(int numDisconnects) throws Exception { CompletableFuture<Void> latch = new CompletableFuture<>(); RabbitMQOptions config = super.config(); ConnectionFactory cf = new ConnectionFactory(); NetClientOptions clientOptions = new NetClientOptions(); if (config.getUri() != null) { cf.setUri(config.getUri()); if (cf.isSSL()) { clientOptions.setSsl(true); clientOptions.setTrustAll(true); } } else { cf.setPort(config.getPort()); cf.setHost(config.getHost()); } String host = cf.getHost(); int port = cf.getPort(); proxyClient = vertx.createNetClient(clientOptions); AtomicInteger remaining = new AtomicInteger(numDisconnects); proxyServer = vertx.createNetServer().connectHandler(serverSocket -> { if (remaining.getAndDecrement() > 0) { serverSocket.close(); } else { serverSocket.pause(); proxyClient.connect(port, host, ar -> { if (ar.succeeded()) { NetSocket clientSocket = ar.result(); serverSocket.handler(clientSocket::write); serverSocket.exceptionHandler(err -> serverSocket.close()); serverSocket.closeHandler(v -> clientSocket.close()); clientSocket.handler(serverSocket::write); clientSocket.exceptionHandler(err -> clientSocket.close()); clientSocket.closeHandler(v -> serverSocket.close()); serverSocket.resume(); } else { serverSocket.close();; } }); } }).listen(PROXY_PORT, "localhost", ar -> { if (ar.succeeded()) { latch.complete(null); } else { latch.completeExceptionally(ar.cause()); } }); latch.get(10, TimeUnit.SECONDS); }
Example 16
Source File: RabbitMqIOTest.java From beam with Apache License 2.0 | 4 votes |
@Test public void testReadQueue() throws Exception { final int maxNumRecords = 10; PCollection<RabbitMqMessage> raw = p.apply( RabbitMqIO.read() .withUri("amqp://guest:guest@localhost:" + port) .withQueue("READ") .withMaxNumRecords(maxNumRecords)); PCollection<String> output = raw.apply( MapElements.into(TypeDescriptors.strings()) .via( (RabbitMqMessage message) -> RabbitMqTestUtils.recordToString(message.getBody()))); List<String> records = RabbitMqTestUtils.generateRecords(maxNumRecords).stream() .map(RabbitMqTestUtils::recordToString) .collect(Collectors.toList()); PAssert.that(output).containsInAnyOrder(records); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("READ", false, false, false, null); for (String record : records) { channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8)); } p.run(); } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
Example 17
Source File: RabbitMqIOTest.java From beam with Apache License 2.0 | 4 votes |
@Test public void testWriteQueue() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = RabbitMqTestUtils.generateRecords(maxNumRecords).stream() .map(RabbitMqMessage::new) .collect(Collectors.toList()); p.apply(Create.of(data)) .apply( RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("TEST", true, false, false, null); Consumer consumer = new RabbitMqTestUtils.TestConsumer(channel, received); channel.basicConsume("TEST", true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
Example 18
Source File: ConnectionFactoryProducer.java From hammock with Apache License 2.0 | 4 votes |
@Produces @ApplicationScoped public ConnectionFactory createConnectionFactory(RabbitMQConfiguration rabbitMQConfiguration) { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setAutomaticRecoveryEnabled(rabbitMQConfiguration.isAutomaticRecovery()); connectionFactory.setClientProperties(rabbitMQConfiguration.getClientProperties()); connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeout()); connectionFactory.setExceptionHandler(rabbitMQConfiguration.getExceptionHandler()); connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeout()); connectionFactory.setHeartbeatExecutor(rabbitMQConfiguration.getHeartbeatExecutor()); connectionFactory.setMetricsCollector(rabbitMQConfiguration.getMetricsCollector()); connectionFactory.setHost(rabbitMQConfiguration.getHost()); connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryInterval()); if(rabbitMQConfiguration.isNio()) { connectionFactory.useNio(); connectionFactory.setNioParams(rabbitMQConfiguration.getNioParams()); } connectionFactory.setPassword(rabbitMQConfiguration.getPassword()); connectionFactory.setPort(rabbitMQConfiguration.getPort()); connectionFactory.setRequestedChannelMax(rabbitMQConfiguration.getRequestedChannelMax()); connectionFactory.setRequestedFrameMax(rabbitMQConfiguration.getRequestedFrameMax()); connectionFactory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestedHeartbeat()); connectionFactory.setSaslConfig(rabbitMQConfiguration.getSaslConfig()); connectionFactory.setSharedExecutor(rabbitMQConfiguration.getSharedExecutor()); connectionFactory.setShutdownExecutor(rabbitMQConfiguration.getShutdownExecutor()); connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeout()); connectionFactory.setSocketConfigurator(rabbitMQConfiguration.getSocketConf()); connectionFactory.setSocketFactory(rabbitMQConfiguration.getFactory()); connectionFactory.setThreadFactory(rabbitMQConfiguration.getThreadFactory()); connectionFactory.setTopologyRecoveryEnabled(rabbitMQConfiguration.isTopologyRecovery()); try { connectionFactory.setUri(rabbitMQConfiguration.getUri()); } catch (Exception e) { throw new RuntimeException("Unable to populate URI ",e); } connectionFactory.setUsername(rabbitMQConfiguration.getUsername()); connectionFactory.setVirtualHost(rabbitMQConfiguration.getVirtualHost()); if(rabbitMQConfiguration.getSslContext() != null) { connectionFactory.useSslProtocol(rabbitMQConfiguration.getSslContext()); } return connectionFactory; }
Example 19
Source File: BrokerAddresses.java From rxrabbit with MIT License | 4 votes |
public BrokerAddressBuilder withUri(URI amqpUri) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException { ConnectionFactory tmp = new ConnectionFactory(); tmp.setUri(amqpUri); cloneConnectionSettings(tmp,amqpUri); return this; }
Example 20
Source File: MockConnectionFactoryTest.java From rabbitmq-mock with Apache License 2.0 | 3 votes |
@Test void configure_by_uri() throws IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException { ConnectionFactory factory = new MockConnectionFactory(); factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost"); Connection connection = factory.newConnection(); assertThat(connection).isInstanceOf(MockConnection.class); }