List of usage examples for com.rabbitmq.client ConnectionFactory setHost
public void setHost(String host)
From source file:com.service.OperationFacadeREST.java
@POST @Override//from w w w .j a va2s .c o m @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public void create(Operation entity) { if (!entity.getState().equals("waiting")) { super.create(entity); return; } if (entity.getOperationType())//venda { ArrayList<ClientStock> l = new ArrayList<>(getEntityManager() .find(Client.class, entity.getFkOwnerId().getClientId()).getClientStockCollection()); Boolean fail = false; for (int i = 0; i < l.size(); i++) { if (l.get(i).getStock().equals(entity.getFkStockId())) { if (l.get(i).getQuantity() < entity.getQuantity()) return; l.get(i).setQuantity(l.get(i).getQuantity() - entity.getQuantity()); getEntityManager().persist(l.get(i)); entity.getFkOwnerId().setClientStockCollection(l); entity.setCreationDate(Date.from(Instant.now())); super.create(entity); } } if (fail) return; } else { entity.setCreationDate(Date.from(Instant.now())); if (entity.getFkStockId().getQuantity() > entity.getQuantity()) { System.out.println("yes"); super.create(entity); } else { return; } } try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello", false, false, false, null); System.out.println(super.findAll().get(super.findAll().size() - 1).getOperationId() + "," + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + "," + entity.getQuantity()); String message = super.findAll().get(super.findAll().size() - 1).getOperationId() + "," + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + "," + entity.getQuantity(); channel.basicPublish("", "hello", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); } catch (IOException ex) { Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex); } catch (TimeoutException ex) { Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.simple.sftpfetch.publish.RabbitClient.java
License:Apache License
/** * Initialize the RabbitClient, establish a connection and declare the exchange * * @param factory the RabbitMQ ConnectionFactory * @param connectionInfo a bean containing the necessary connection information * * @throws NoSuchAlgorithmException// w ww .j a v a 2 s .co m * @throws KeyManagementException * @throws URISyntaxException * @throws IOException */ public RabbitClient(ConnectionFactory factory, RabbitConnectionInfo connectionInfo) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException { factory.setHost(connectionInfo.getHostname()); factory.setPort(connectionInfo.getPort()); factory.setUsername(connectionInfo.getUsername()); factory.setPassword(connectionInfo.getPassword()); factory.setVirtualHost(connectionInfo.getVhost()); factory.setConnectionTimeout(connectionInfo.getTimeout()); Connection conn = factory.newConnection(); exchange = connectionInfo.getExchange(); channel = conn.createChannel(); channel.exchangeDeclare(exchange, EXCHANGE_TYPE, true); this.amqpProperties = new AMQP.BasicProperties.Builder().contentType(CONTENT_TYPE).deliveryMode(2).build(); }
From source file:com.siva.rabbitmq.AmqpMsgPublisher.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("admin"); factory.setPassword("welcome01"); factory.setPort(5672);// w w w . ja va 2s . c o m factory.setVirtualHost("/admin_vhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); String routingKey = "mqtt_topic.iot.admin_vhost"; String message = "Test Message from IoT"; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); connection.close(); }
From source file:com.surgeplay.visage.master.VisageMaster.java
License:Open Source License
@Override public void run() { try {/* w w w. j a v a2 s . c o m*/ Log.setLog(new LogShim(Visage.log)); long total = Runtime.getRuntime().totalMemory(); long max = Runtime.getRuntime().maxMemory(); if (Visage.debug) Visage.log.finer("Current heap size: " + humanReadableByteCount(total, false)); if (Visage.debug) Visage.log.finer("Max heap size: " + humanReadableByteCount(max, false)); if (total < max) { Visage.log.warning( "You have set your minimum heap size (Xms) lower than the maximum heap size (Xmx) - this can cause GC thrashing. It is strongly recommended to set them both to the same value."); } if (max < (1000 * 1000 * 1000)) { Visage.log.warning( "The heap size (Xmx) is less than one gigabyte; it is recommended to run Visage with a gigabyte or more. Use -Xms1G and -Xmx1G to do this."); } Visage.log.info("Setting up Jetty"); Server server = new Server( new InetSocketAddress(config.getString("http.bind"), config.getInt("http.port"))); List<String> expose = config.getStringList("expose"); String poweredBy; if (expose.contains("server")) { if (expose.contains("version")) { poweredBy = "Visage v" + Visage.VERSION; } else { poweredBy = "Visage"; } } else { poweredBy = null; } ResourceHandler resource = new ResourceHandler(); resource.setResourceBase(config.getString("http.static")); resource.setDirectoriesListed(false); resource.setWelcomeFiles(new String[] { "index.html" }); resource.setHandler(new VisageHandler(this)); if (!"/dev/null".equals(config.getString("log"))) { new File(config.getString("log")).getParentFile().mkdirs(); server.setRequestLog(new AsyncNCSARequestLog(config.getString("log"))); } GzipHandler gzip = new GzipHandler(); gzip.setHandler(new HeaderHandler("X-Powered-By", poweredBy, resource)); server.setHandler(gzip); String redisHost = config.getString("redis.host"); int redisPort = config.getInt("redis.port"); Visage.log.info("Connecting to Redis at " + redisHost + ":" + redisPort); resolverNum = config.getInt("redis.resolver-db"); skinNum = config.getInt("redis.skin-db"); JedisPoolConfig jpc = new JedisPoolConfig(); jpc.setMaxIdle(config.getInt("redis.max-idle-connections")); jpc.setMaxTotal(config.getInt("redis.max-total-connections")); jpc.setMinIdle(config.getInt("redis.min-idle-connections")); if (config.hasPath("redis.password")) { password = config.getString("redis.password"); } pool = new JedisPool(jpc, redisHost, redisPort); Visage.log.info("Connecting to RabbitMQ at " + config.getString("rabbitmq.host") + ":" + config.getInt("rabbitmq.port")); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(config.getString("rabbitmq.host")); factory.setPort(config.getInt("rabbitmq.port")); factory.setRequestedHeartbeat(10); if (config.hasPath("rabbitmq.user")) { factory.setUsername(config.getString("rabbitmq.user")); factory.setPassword(config.getString("rabbitmq.password")); } String queue = config.getString("rabbitmq.queue"); Closer closer = Closer.create(); steve = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("steve.png"))); alex = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("alex.png"))); closer.close(); conn = factory.newConnection(); channel = conn.createChannel(); if (Visage.debug) Visage.log.finer("Setting up queue '" + queue + "'"); channel.queueDeclare(queue, false, false, true, null); channel.basicQos(1); if (Visage.debug) Visage.log.finer("Setting up reply queue"); replyQueue = channel.queueDeclare().getQueue(); consumer = new QueueingConsumer(channel); channel.basicConsume(replyQueue, consumer); if (config.getBoolean("slave.enable")) { Visage.log.info("Starting fallback slave"); fallback = new VisageSlave( config.getConfig("slave").withValue("rabbitmq", config.getValue("rabbitmq"))); fallback.start(); } Visage.log.info("Starting Jetty"); server.start(); Visage.log.info("Listening for finished jobs"); try { while (run) { Delivery delivery = consumer.nextDelivery(); if (Visage.trace) Visage.log.finest("Got delivery"); try { String corrId = delivery.getProperties().getCorrelationId(); if (queuedJobs.containsKey(corrId)) { if (Visage.trace) Visage.log.finest("Valid"); responses.put(corrId, delivery.getBody()); Runnable run = queuedJobs.get(corrId); queuedJobs.remove(corrId); if (Visage.trace) Visage.log.finest("Removed from queue"); run.run(); if (Visage.trace) Visage.log.finest("Ran runnable"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); if (Visage.trace) Visage.log.finest("Ack'd"); } else { Visage.log.warning("Unknown correlation ID?"); channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false); } } catch (Exception e) { Visage.log.log(Level.WARNING, "An unexpected error occured while attempting to process a response.", e); } } } catch (InterruptedException e) { } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occured in the master run loop.", e); System.exit(2); } try { Visage.log.info("Shutting down master"); server.stop(); pool.destroy(); conn.close(5000); } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred while shutting down the master.", e); } } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occured while initializing the master.", e); System.exit(1); } }
From source file:com.trivago.mail.pigeon.queue.ConnectionPool.java
License:Apache License
public static Connection getConnection() { if (connection == null) { ConnectionFactory factory = new ConnectionFactory(); Configuration configuration = settings.getConfiguration(); factory.setUsername(configuration.getString("rabbit.username")); factory.setPassword(configuration.getString("rabbit.password")); factory.setVirtualHost(configuration.getString("rabbit.vhost")); factory.setHost(configuration.getString("rabbit.hostname")); factory.setPort(configuration.getInt("rabbit.port")); try {//from w w w . java2 s . c om connection = factory.newConnection(); } catch (IOException e) { log.error(e); throw new RuntimeException(e); } } return connection; }
From source file:com.UseCaseSimpleConsumer.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try {// ww w .j a v a2 s .co m channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); } try { channel.queueDeclarePassive(ROUTE_KEY); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.queueDeclare(ROUTE_KEY, false, false, false, null); } channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY); String param = "IBM"; String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + " <m:order>\n" + " <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + " <m:quantity>" + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + " <m:symbol>" + param + "</m:symbol>\n" + " </m:order>\n" + "</m:placeOrder>"; channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY, new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes()); System.out.println(" [x] Sent '" + msg + "'"); channel.close(); connection.close(); }
From source file:com.UseCaseSimpleProducer.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try {//from w w w. j a va2s . c o m channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { channel.exchangeDeclare(EXCHANGE_NAME, "direct"); } try { channel.queueDeclarePassive(QUEUE_NAME); } catch (java.io.IOException e) { channel.queueDeclare(QUEUE_NAME, false, false, false, null); } channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); } }
From source file:com.vmware.bdd.manager.RuntimeConnectionManager.java
License:Open Source License
/** * Setup rabbitMQ exchange and channel to notify VHMs * @throws IOException /*from w ww .ja v a2 s.c o m*/ */ public void init() throws IOException { String serverHost = ConfigInfo.getMqServerHost(); int serverPort = ConfigInfo.getMqServerPort(); String serverUsername = ConfigInfo.getMqServerUsername(); String serverPassword = ConfigInfo.getMqServerPassword(); logger.info("init runtime exchange"); ConnectionFactory factory = new ConnectionFactory(); if (serverUsername != null && !serverUsername.equals("")) { factory.setUsername(serverUsername); factory.setPassword(serverPassword); } factory.setVirtualHost("/"); factory.setHost(serverHost); factory.setPort(serverPort); try { conn = factory.newConnection(); runtimeChannel = conn.createChannel(); logger.info("creating exchange: " + exchangeName); runtimeChannel.exchangeDeclare(exchangeName, "direct", true, // durable false, // auto-delete null); // arguments map } catch (IOException e) { logger.error(e.getMessage()); destroy(); throw e; } }
From source file:com.vmware.bdd.utils.RabbitMQConsumer.java
License:Open Source License
/** * Receive and process each message until the listener indicating. A new * queue will be created when start and will be deleted when stopping * receiving message./*from ww w. j av a2s . c o m*/ * * FIXME Is it a best practice to create one queue for one task? Or we should * create one thread to handle all messages? * * @param listener * message processor callback * @throws IOException */ public void processMessage(MessageListener listener) throws IOException { ConnectionFactory factory = new ConnectionFactory(); if (username != null && !username.equals("")) { factory.setUsername(username); factory.setPassword(password); } factory.setVirtualHost("/"); factory.setHost(host); factory.setPort(port); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); /** * make exchange and queue non-durable */ channel.exchangeDeclare(exchangeName, "direct", true); if (!getQueue) { channel.queueDeclare(queueName, false, true, true, null); } else { queueName = channel.queueDeclare().getQueue(); } channel.queueBind(queueName, exchangeName, routingKey); boolean noAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, noAck, consumer); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(mqRecvTimeoutMs); } catch (InterruptedException e) { logger.warn("message consumer interrupted", e); continue; } if (delivery == null) { logger.debug("timeout, no message received"); if (stopping && new Date().after(mqExpireTime)) { logger.error("stop receiving messages without normal termination"); break; } continue; } String message = new String(delivery.getBody()); if (graceStopping) { extendExpirationTime(); } logger.info("message received: " + message); try { if (!listener.onMessage(message)) { logger.info("stop receiving messages normally"); break; } } catch (Throwable t) { logger.error("calling message listener failed", t); // discard and continue in non-debug mode AuAssert.unreachable(); } channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } try { channel.queueDelete(queueName); } catch (AlreadyClosedException e) { logger.error("failed to delete queue: " + queueName, e); } try { channel.close(); } catch (AlreadyClosedException e) { logger.error("failed to close channel, queue: " + queueName, e); } try { conn.close(); } catch (AlreadyClosedException e) { logger.error("failed to close connection, queue: " + queueName, e); } }
From source file:com.wakkir.rabbitmq.basic.Reciever.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); 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) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received '" + message + "'"); }/* w w w.j a v a 2 s . co m*/ }