List of usage examples for com.rabbitmq.client ConnectionFactory setRequestedHeartbeat
public void setRequestedHeartbeat(int requestedHeartbeat)
From source file:biospectra.classify.server.RabbitMQInputClient.java
License:Apache License
public synchronized void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); String hostname = this.conf.getRabbitMQHostnames().get(this.hostId); factory.setHost(hostname);/*from www .jav a2s . c om*/ factory.setPort(this.conf.getRabbitMQPort()); factory.setUsername(this.conf.getRabbitMQUserId()); factory.setPassword(this.conf.getRabbitMQUserPwd()); factory.setRequestedHeartbeat(60); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.shutdownListener = new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException sse) { LOG.error("connection shutdown", sse); } }; this.connection.addShutdownListener(this.shutdownListener); this.requestChannel = this.connection.createChannel(); this.responseChannel = this.connection.createChannel(); LOG.info("reader connected - " + hostname + ":" + this.conf.getRabbitMQPort()); this.responseChannel.basicQos(10); this.queueName = this.responseChannel.queueDeclare().getQueue(); this.consumer = new DefaultConsumer(this.responseChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); this.getChannel().basicAck(envelope.getDeliveryTag(), false); LOG.info("> " + message); ClassificationResponseMessage res = ClassificationResponseMessage.createInstance(message); ClassificationRequest ereq = null; synchronized (requestMap) { ereq = requestMap.get(res.getReqId()); if (ereq != null) { requestMap.remove(res.getReqId()); } } if (ereq == null) { LOG.error("cannot find matching request"); } else { ClassificationResponse eres = new ClassificationResponse(ereq, res); boolean responded = false; synchronized (ereq) { ClassificationRequest.RequestStatus status = ereq.getStatus(); if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) { ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_RESPONDED); responded = true; } requestQueue.remove(ereq); } if (responded) { LOG.info("res : " + ereq.getReqId()); if (handler != null) { handler.onSuccess(eres.getReqId(), eres.getHeader(), eres.getSequence(), eres.getResult(), eres.getType(), eres.getTaxonRank(), eres.getTaxonName()); } synchronized (requestQueue) { requestQueue.notifyAll(); } } } } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { responseChannel.basicConsume(queueName, consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); this.reachable = true; this.timeoutThread = new Thread(new Runnable() { @Override public void run() { while (true) { boolean cont = false; if (requestQueue.size() > 0) { ClassificationRequest ereq = requestQueue.peek(); Date cur = new Date(); if (ereq != null && cur.getTime() - ereq.getSentTime() >= QUERY_TIMEOUT) { LOG.info("found timeout request"); //timeout boolean timeout = false; synchronized (ereq) { ClassificationRequest.RequestStatus status = ereq.getStatus(); if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) { ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_TIMEOUT); timeout = true; } requestQueue.remove(ereq); } synchronized (requestMap) { requestMap.remove(ereq.getReqId()); } if (timeout) { LOG.info("timeout : " + ereq.getReqId()); handler.onTimeout(ereq.getReqId(), ereq.getHeader(), ereq.getSequence()); synchronized (requestQueue) { requestQueue.notifyAll(); } } cont = true; } } if (!cont) { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } } } } }); this.timeoutThread.start(); }
From source file:biospectra.classify.server.RabbitMQInputServer.java
License:Apache License
public synchronized void connect() throws IOException, TimeoutException { LOG.info("Connecting to - " + this.conf.getRabbitMQHostname() + ":" + this.conf.getRabbitMQPort()); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.conf.getRabbitMQHostname()); factory.setPort(this.conf.getRabbitMQPort()); factory.setUsername(this.conf.getRabbitMQUserId()); factory.setPassword(this.conf.getRabbitMQUserPwd()); factory.setRequestedHeartbeat(60); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.connection.addShutdownListener(new ShutdownListener() { @Override//from ww w .j ava 2 s. com public void shutdownCompleted(ShutdownSignalException sse) { LOG.error("connection shutdown", sse); } }); this.requestChannel = this.connection.createChannel(); this.responseChannel = this.connection.createChannel(); LOG.info("connected."); this.requestChannel.basicQos(1); this.requestChannel.queueDeclare("request", false, false, true, null); this.responseChannel.addReturnListener(new ReturnListener() { @Override public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); LOG.info("message not delivered to " + routingKey); LOG.info(message); } }); this.consumer = new DefaultConsumer(this.requestChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); this.getChannel().basicAck(envelope.getDeliveryTag(), false); if (handler != null) { ClassificationRequestMessage req = ClassificationRequestMessage.createInstance(message); handler.handleMessage(req, properties.getReplyTo()); } } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { requestChannel.basicConsume("request", consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); }
From source file:com.jbrisbin.vcloud.session.CloudStore.java
License:Apache License
protected synchronized Connection getMqConnection() throws IOException { if (null == mqConnection) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(mqHost);/*from ww w . j av a 2 s . c o m*/ factory.setPort(mqPort); factory.setUsername(mqUser); factory.setPassword(mqPassword); factory.setVirtualHost(mqVirtualHost); factory.setRequestedHeartbeat(10); mqConnection = factory.newConnection(); } return mqConnection; }
From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java
License:Apache License
private ConnectionFactory getOrCreateConnectionFactory() { if (connectionFactory == null) { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(getUsername()); factory.setPassword(getPassword()); factory.setVirtualHost(getVhost()); factory.setHost(getHostname());/*from w w w .jav a2s . c o m*/ factory.setPort(getPortNumber()); if (getClientProperties() != null) { factory.setClientProperties(getClientProperties()); } factory.setConnectionTimeout(getConnectionTimeout()); factory.setRequestedChannelMax(getRequestedChannelMax()); factory.setRequestedFrameMax(getRequestedFrameMax()); factory.setRequestedHeartbeat(getRequestedHeartbeat()); if (getSslProtocol() != null) { try { if (getSslProtocol().equals("true")) { factory.useSslProtocol(); } else if (getTrustManager() == null) { factory.useSslProtocol(getSslProtocol()); } else { factory.useSslProtocol(getSslProtocol(), getTrustManager()); } } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalArgumentException("Invalid sslProtocol " + sslProtocol, e); } } if (getAutomaticRecoveryEnabled() != null) { factory.setAutomaticRecoveryEnabled(getAutomaticRecoveryEnabled()); } if (getNetworkRecoveryInterval() != null) { factory.setNetworkRecoveryInterval(getNetworkRecoveryInterval()); } if (getTopologyRecoveryEnabled() != null) { factory.setTopologyRecoveryEnabled(getTopologyRecoveryEnabled()); } connectionFactory = factory; } return connectionFactory; }
From source file:com.paxxis.cornerstone.messaging.service.amqp.AMQPServiceBusConnector.java
License:Apache License
protected void initConnection() { try {/*from w w w.j a v a2 s . c o m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); factory.setAutomaticRecoveryEnabled(autoRecover); factory.setConnectionTimeout(timeout); factory.setNetworkRecoveryInterval(recoveryInterval); factory.setRequestedHeartbeat(heartbeat); factory.setTopologyRecoveryEnabled(autoTopologyRecover); factory.setExceptionHandler(exceptionHandler); connection = factory.newConnection(); session = (AMQPSession) createSession(); } catch (IOException e) { logger.error(e); throw new RuntimeException(e); } }
From source file:com.surgeplay.visage.master.VisageMaster.java
License:Open Source License
@Override public void run() { try {//from ww w. j a v a 2s . 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.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java
License:Open Source License
/** * Build an instance./* ww w .j ava2 s . com*/ * * @param lifecycle The current application lifecyle * @param configuration The current application configuration * @since 16.05.19 */ @Inject public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) { this.configuration = configuration; try { final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI); if (uri == null || uri.isEmpty()) { throw new RuntimeException("URI is empty"); } final ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri(uri); connectionFactory .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT)); connectionFactory .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY)); connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT)); connectionFactory.setAutomaticRecoveryEnabled( configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY)); if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) { connectionFactory.useSslProtocol(); } final ExecutorService es = Executors .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR)); this.rabbitConnection = connectionFactory.newConnection(es); RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}", String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "", connectionFactory.getHost(), connectionFactory.getPort(), connectionFactory.getVirtualHost())); } catch (Exception ex) { this.rabbitConnection = null; if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) { RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex); throw new RuntimeException(ex); } else { RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage()); } } lifecycle.addStopHook(() -> { RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ"); if (this.rabbitConnection != null) { this.rabbitConnection.close(); } return CompletableFuture.completedFuture(null); }); }
From source file:io.bootique.rabbitmq.client.connection.ConnectionConfig.java
License:Apache License
public Connection createConnection(String connectionName) { com.rabbitmq.client.ConnectionFactory factory = createConnectionFactory(); factory.setRequestedChannelMax(requestedChannelMax); factory.setRequestedFrameMax(requestedFrameMax); factory.setRequestedHeartbeat(requestedHeartbeat); factory.setConnectionTimeout(connectionTimeout); factory.setHandshakeTimeout(handshakeTimeout); factory.setShutdownTimeout(shutdownTimeout); factory.setAutomaticRecoveryEnabled(automaticRecoveryEnabled); factory.setTopologyRecoveryEnabled(topologyRecovery); factory.setNetworkRecoveryInterval(networkRecoveryInterval); LOGGER.info("Creating RabbitMQ connection."); try {/*from www . j a v a 2s.co m*/ return factory.newConnection(); } catch (IOException | TimeoutException e) { throw new RuntimeException(String.format("Can't create connection \"%s\".", connectionName), e); } }
From source file:kieker.analysis.plugin.reader.amqp.AMQPReader.java
License:Apache License
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(); }
From source file:kieker.monitoring.writer.amqp.AmqpWriter.java
License:Apache License
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(); }