Java Code Examples for com.rabbitmq.client.ConnectionFactory#setVirtualHost()
The following examples show how to use
com.rabbitmq.client.ConnectionFactory#setVirtualHost() .
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: RabbitMqConnFactoryUtil.java From springboot-learn with MIT License | 6 votes |
/** * 获取rabbit连接 */ public static Connection getRabbitConn() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("192.168.242.131"); factory.setPort(5672); Connection conn = factory.newConnection(); //高级连接使用线程池 // ExecutorService es = Executors.newFixedThreadPool(20); // Connection conn = factory.newConnection(es); return conn; }
Example 2
Source File: RabbitMQClient.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
public RabbitMQClient(RabbitMQOptions rabbitMQOptions) { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUsername(rabbitMQOptions.username); connectionFactory.setPassword(rabbitMQOptions.password); connectionFactory.setVirtualHost(rabbitMQOptions.virtualHost); connectionFactory.setHost(rabbitMQOptions.host); connectionFactory.setPort(rabbitMQOptions.port); connectionFactory.setSharedExecutor(workers); connectionFactory.setAutomaticRecoveryEnabled(true); GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMinIdle(8); genericObjectPoolConfig.setMaxTotal(18); genericObjectPoolConfig.setMinIdle(8); pool = new GenericObjectPool<>(new RabbitMQChannelFactory(createConnection(connectionFactory)), genericObjectPoolConfig); }
Example 3
Source File: Events.java From rabbitmqexample with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Down Stream server ip (localhost):"); String server_ip = br.readLine(); if (server_ip.equalsIgnoreCase("")) { server_ip = "localhost"; } ConnectionFactory factory_down = new ConnectionFactory(); factory_down.setHost(server_ip); factory_down.setUsername("test"); factory_down.setPassword("test"); factory_down.setVirtualHost("poc"); Connection connection_down = factory_down.newConnection(); System.out.println("Connected to Down Stream node: " + server_ip); final Channel channel_down = connection_down.createChannel(); final String exchange = "service"; channel_down.exchangeDeclare(exchange, "topic", true); channel_down.basicPublish(exchange, "r1.gis", MessageProperties.PERSISTENT_BASIC, "better".getBytes()); }
Example 4
Source File: Producer.java From code with Apache License 2.0 | 6 votes |
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 exchange = "test_consumer_exchange"; String routingKey = "consumer.save"; String msg = "Hello RabbitMQ Consumer Message"; for (int i = 0; i < 5; i++) { channel.basicPublish(exchange, routingKey, true, null, msg.getBytes()); } }
Example 5
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
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 6
Source File: RabbitMQ.java From judgels with GNU General Public License v2.0 | 5 votes |
@Inject public RabbitMQ(RabbitMQConfiguration config) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(config.getHost()); factory.setPort(config.getPort()); factory.setUsername(config.getUsername()); factory.setPassword(config.getPassword()); factory.setVirtualHost(config.getVirtualHost()); this.connectionFactory = factory; }
Example 7
Source File: Consumer4DirectExchange.java From code with Apache License 2.0 | 5 votes |
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: MQConfig.java From jseckill with Apache License 2.0 | 5 votes |
@Bean("mqConnectionSeckill") public Connection mqConnectionSeckill(@Autowired MQConfigBean mqConfigBean) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); //用户名 factory.setUsername(username); //密码 factory.setPassword(password); //虚拟主机路径(相当于数据库名) factory.setVirtualHost(virtualHost); //返回连接 return factory.newConnection(mqConfigBean.getAddressList()); }
Example 9
Source File: Producer.java From code with Apache License 2.0 | 5 votes |
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 exchange = "test_ack_exchange"; String routingKey = "ack.save"; for(int i =0; i<5; i ++){ Map<String, Object> headers = new HashMap<String, Object>(); headers.put("num", i); AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .deliveryMode(2) .contentEncoding("UTF-8") .headers(headers) .build(); String msg = "Hello RabbitMQ ACK Message " + i; channel.basicPublish(exchange, routingKey, true, properties, msg.getBytes()); } }
Example 10
Source File: Producer.java From code with Apache License 2.0 | 5 votes |
/** * 1.消息被拒绝(basic.reject/ basic.nack)并且requeue=false(没有重回队列) * 2.消息TTL过期 * 3.队列达到最大长度 */ 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 exchange = "test_dlx_exchange"; String routingKey = "dlx.save"; String msg = "Hello RabbitMQ DLX Message"; for(int i =0; i<1; i ++){ AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .deliveryMode(2) .contentEncoding("UTF-8") .expiration("10000") .build(); channel.basicPublish(exchange, routingKey, true, properties, msg.getBytes()); } }
Example 11
Source File: MQConfig.java From jseckill with Apache License 2.0 | 5 votes |
@Bean("mqConnectionReceive") public Connection mqConnectionReceive(@Autowired MQConfigBean mqConfigBean) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); //用户名 factory.setUsername(username); //密码 factory.setPassword(password); //虚拟主机路径(相当于数据库名) factory.setVirtualHost(virtualHost); //返回连接 return factory.newConnection(mqConfigBean.getAddressList()); }
Example 12
Source File: Producer.java From code with Apache License 2.0 | 5 votes |
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 通过连接工厂创建连接 Connection connection = connectionFactory.newConnection(); //3 通过connection创建一个Channel Channel channel = connection.createChannel(); // 自定义属性 Map<String, Object> headers = new HashMap<>(); headers.put("my1", "111"); headers.put("my2", "222"); AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder() .deliveryMode(2) .contentEncoding("UTF-8") .expiration("10000") .headers(headers) .build(); //4 通过Channel发送数据 for(int i=0; i < 5; i++){ String msg = "Hello RabbitMQ!"; //1 exchange 2 routingKey channel.basicPublish("", "test001", properties, msg.getBytes()); } //5 记得要关闭相关的连接 channel.close(); connection.close(); }
Example 13
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
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 通过连接工厂创建连接 Connection connection = connectionFactory.newConnection(); //3 通过connection创建一个Channel Channel channel = connection.createChannel(); //4 声明(创建)一个队列 String queueName = "test001"; channel.queueDeclare(queueName, true, false, false, null); //5 创建消费者 QueueingConsumer queueingConsumer = new QueueingConsumer(channel); //6 设置Channel channel.basicConsume(queueName, true, queueingConsumer); while (true) { //7 获取消息 Delivery delivery = queueingConsumer.nextDelivery(); String msg = new String(delivery.getBody()); System.err.println("消费端: " + msg); Map<String, Object> headers = delivery.getProperties().getHeaders(); System.err.println("headers get my1 value: " + headers.get("my1") + "\tmy1 value:" + headers.get("my2")); //Envelope envelope = delivery.getEnvelope(); } }
Example 14
Source File: RabbitMqClientDemo.java From xian with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(XianConfig.get("rabbitmqUserName")); factory.setPassword(XianConfig.get("rabbitmqPwd")); factory.setVirtualHost("/"); factory.setHost("production-internet-mq.apaycloud.com"); factory.setPort(5672); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); String exchangeName = "yy-exchange"; String routingKey = "yy-routingKey"; String queueName = "yy-queueName"; channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); byte[] messageBodyBytes = "Hello, world2!".getBytes(); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); Thread.sleep(1000 * 60); channel.close(); conn.close(); }
Example 15
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
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 16
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //1、创建一个ConnectionFactory, 并进行配置 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(Constant.ip); connectionFactory.setPort(Constant.port); connectionFactory.setVirtualHost("/"); //2、通过连接工厂创建连接 Connection connection = connectionFactory.newConnection(); //3、通过connection创建一个Channel Channel channel = connection.createChannel(); //4、声明(创建)一个队列 String queueName = "test001"; channel.queueDeclare(queueName, true, false, false, null); //5、创建消费者 QueueingConsumer queueingConsumer = new QueueingConsumer(channel); //6、设置channel channel.basicConsume(queueName, true, queueingConsumer); while (true) { //7、 获取消息 QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery(); String msg = new String(delivery.getBody()); System.err.println("消费端: " + msg); //Envelope envelope = delivery.getEnvelope(); } }
Example 17
Source File: Consumer.java From code with Apache License 2.0 | 4 votes |
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_ack_exchange"; String queueName = "test_ack_queue"; String routingKey = "ack.#"; channel.exchangeDeclare(exchangeName, "topic", true, false, null); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); // 手工签收 必须要关闭 autoAck = false channel.basicConsume(queueName, false, new MyConsumer(channel)); }
Example 18
Source File: SharedRabbitMQResource.java From baleen with Apache License 2.0 | 4 votes |
@Override protected boolean doInitialize( final ResourceSpecifier aSpecifier, final Map<String, Object> aAdditionalParams) throws ResourceInitializationException { try { final ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(username); factory.setPassword(password); factory.setVirtualHost(virtualHost); factory.setHost(host); factory.setPort(port); if (useHttps) { if (trustAll) { factory.useSslProtocol(); } else { try (FileInputStream keystoreStream = new FileInputStream(keystorePath); FileInputStream trustStoreStream = new FileInputStream(truststorePath); ) { KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(keystoreStream, keystorePass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, keystorePass.toCharArray()); KeyStore tks = KeyStore.getInstance("JKS"); tks.load(trustStoreStream, truststorePass.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(tks); SSLContext c = SSLContext.getInstance(sslProtocol); c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); factory.useSslProtocol(c); } } } connection = factory.newConnection(); } catch (final Exception e) { throw new ResourceInitializationException( new BaleenException("Error connecting to RabbitMQ", e)); } getMonitor().info("Initialised shared RabbitMQ resource"); return true; }
Example 19
Source File: EmbeddedRabbitMqTest.java From embedded-rabbitmq with Apache License 2.0 | 4 votes |
@Test public void start() throws Exception { File configFile = temporaryFolder.newFile("rabbitmq.conf"); PrintWriter writer = new PrintWriter(configFile, "UTF-8"); writer.println("log.connection.level = debug"); writer.println("log.channel.level = debug"); writer.close(); EmbeddedRabbitMqConfig config = new EmbeddedRabbitMqConfig.Builder() // .version(PredefinedVersion.V3_8_0) .version(new BaseVersion("3.8.1")) .randomPort() .downloadFrom(OfficialArtifactRepository.GITHUB) // .downloadFrom(new URL("https://github.com/rabbitmq/rabbitmq-server/releases/download/rabbitmq_v3_6_6_milestone1/rabbitmq-server-mac-standalone-3.6.5.901.tar.xz"), "rabbitmq_server-3.6.5.901") // .envVar(RabbitMqEnvVar.NODE_PORT, String.valueOf(PORT)) .envVar(RabbitMqEnvVar.CONFIG_FILE, configFile.toString().replace(".conf", "")) .extractionFolder(temporaryFolder.newFolder("extracted")) .rabbitMqServerInitializationTimeoutInMillis(TimeUnit.SECONDS.toMillis(20)) .defaultRabbitMqCtlTimeoutInMillis(TimeUnit.SECONDS.toMillis(20)) .erlangCheckTimeoutInMillis(TimeUnit.SECONDS.toMillis(10)) // .useCachedDownload(false) .build(); rabbitMq = new EmbeddedRabbitMq(config); rabbitMq.start(); LOGGER.info("Back in the test!"); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setPort(config.getRabbitMqPort()); connectionFactory.setVirtualHost("/"); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); Connection connection = connectionFactory.newConnection(); assertThat(connection.isOpen(), equalTo(true)); Channel channel = connection.createChannel(); assertThat(channel.isOpen(), equalTo(true)); ProcessResult listUsersResult = new RabbitMqCtl(config, Collections.singletonMap("TEST_ENV_VAR", "FooBar")) .execute("list_users") .get(); assertThat(listUsersResult.getExitValue(), is(0)); assertThat(listUsersResult.getOutput().getString(), containsString("guest")); RabbitMqPlugins rabbitMqPlugins = new RabbitMqPlugins(config); Map<Plugin.State, Set<Plugin>> groupedPlugins = rabbitMqPlugins.groupedList(); assertThat(groupedPlugins.get(Plugin.State.ENABLED_EXPLICITLY).size(), equalTo(0)); rabbitMqPlugins.enable("rabbitmq_management"); Plugin plugin = rabbitMqPlugins.list().get("rabbitmq_management"); assertThat(plugin, is(notNullValue())); assertThat(plugin.getState(), hasItems(Plugin.State.ENABLED_EXPLICITLY, Plugin.State.RUNNING)); HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:15672").openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); assertThat(urlConnection.getResponseCode(), equalTo(200)); urlConnection.disconnect(); rabbitMqPlugins.disable("rabbitmq_management"); channel.close(); connection.close(); }
Example 20
Source File: AbstractAMQPProcessor.java From nifi with Apache License 2.0 | 4 votes |
protected Connection createConnection(ProcessContext context) { final ConnectionFactory cf = new ConnectionFactory(); cf.setHost(context.getProperty(HOST).evaluateAttributeExpressions().getValue()); cf.setPort(Integer.parseInt(context.getProperty(PORT).evaluateAttributeExpressions().getValue())); cf.setUsername(context.getProperty(USER).evaluateAttributeExpressions().getValue()); cf.setPassword(context.getProperty(PASSWORD).getValue()); final String vHost = context.getProperty(V_HOST).evaluateAttributeExpressions().getValue(); if (vHost != null) { cf.setVirtualHost(vHost); } // handles TLS/SSL aspects final Boolean useCertAuthentication = context.getProperty(USE_CERT_AUTHENTICATION).asBoolean(); final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); // if the property to use cert authentication is set but the SSL service hasn't been configured, throw an exception. if (useCertAuthentication && sslService == null) { throw new IllegalStateException("This processor is configured to use cert authentication, " + "but the SSL Context Service hasn't been configured. You need to configure the SSL Context Service."); } final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue(); if (sslService != null) { final SslContextFactory.ClientAuth clientAuth; if (StringUtils.isBlank(rawClientAuth)) { clientAuth = SslContextFactory.ClientAuth.REQUIRED; } else { try { clientAuth = SslContextFactory.ClientAuth.valueOf(rawClientAuth); } catch (final IllegalArgumentException iae) { throw new IllegalStateException(String.format("Unrecognized client auth '%s'. Possible values are [%s]", rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", "))); } } final SSLContext sslContext = sslService.createSSLContext(clientAuth); cf.useSslProtocol(sslContext); if (useCertAuthentication) { // this tells the factory to use the cert common name for authentication and not user name and password // REF: https://github.com/rabbitmq/rabbitmq-auth-mechanism-ssl cf.setSaslConfig(DefaultSaslConfig.EXTERNAL); } } try { Connection connection = cf.newConnection(); return connection; } catch (Exception e) { throw new IllegalStateException("Failed to establish connection with AMQP Broker: " + cf.toString(), e); } }