List of usage examples for com.rabbitmq.client ConnectionFactory newConnection
public Connection newConnection() throws IOException, TimeoutException
From source file:org.hobbit.core.rabbit.EchoServer.java
License:Open Source License
@Override public void run() { running = true;/* w w w. j a v a 2s . c o m*/ Connection connection = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitHost); connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicQos(1); channel.queueDeclare(queueName, false, false, true, null); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).deliveryMode(2).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, body); } }; channel.basicConsume(queueName, true, consumer); while (running) { Thread.sleep(3000); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException e) { } } } }
From source file:org.hobbit.core.rabbit.FileStreamingTest.java
License:Open Source License
@Before public void before() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(TestConstants.RABBIT_HOST); connection = factory.newConnection(); }
From source file:org.hobbit.core.rabbit.ParallelizationTest.java
License:Open Source License
@Test public void test() throws InterruptedException, IOException, TimeoutException { EchoServer server = new EchoServer(TestConstants.RABBIT_HOST, REQUEST_QUEUE_NAME); Thread serverThread = new Thread(server); serverThread.start();/*ww w.j a v a 2s.c om*/ System.out.println("Server started."); Random rand = new Random(); Thread clientThreads[] = new Thread[NUMBER_OF_CLIENTS]; RabbitRpcClient client = null; Connection connection = null; long time; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(TestConstants.RABBIT_HOST); connection = factory.newConnection(); client = RabbitRpcClient.create(connection, REQUEST_QUEUE_NAME); for (int i = 0; i < clientThreads.length; ++i) { clientThreads[i] = new Thread( new RpcClientBasedEchoClient(client, NUMBER_OF_MSGS, rand.nextLong())); } Timer timer = new Timer(); final Thread testThread = Thread.currentThread(); timer.schedule(new TimerTask() { @SuppressWarnings("deprecation") @Override public void run() { testThread.stop(); } }, MAX_RUNTIME); time = System.currentTimeMillis(); for (int i = 0; i < clientThreads.length; ++i) { clientThreads[i].start(); System.out.print("Client #"); System.out.print(i); System.out.println(" started."); } for (int i = 0; i < clientThreads.length; ++i) { clientThreads[i].join(); System.out.print("Client #"); System.out.print(i); System.out.println(" terminated."); } server.setRunning(false); serverThread.join(); timer.cancel(); time = System.currentTimeMillis() - time; System.out.println("Server terminated."); System.out.println("runtime : " + time + "ms"); } finally { if (client != null) { client.close(); } if (connection != null) { connection.close(); } } }
From source file:org.hp.samples.ProcessMessage.java
License:Open Source License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(200);/*from w w w.ja v a2 s .c om*/ PrintWriter writer = response.getWriter(); writer.println("Here's your message:"); // Pull out the RABBITMQ_URL environment variable String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // Create the queue channel.queueDeclare("hello", false, false, false, null); String routingKey = "thekey"; String exchangeName = "exchange"; // Declare an exchange and bind it to the queue channel.exchangeDeclare(exchangeName, "direct", true); channel.queueBind("hello", exchangeName, routingKey); // Grab the message from the HTML form and publish it to the queue String message = request.getParameter("message"); channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); writer.println(" Message sent to queue '" + message + "'"); boolean autoAck = false; // Get the response message GetResponse responseMsg = channel.basicGet("hello", autoAck); if (responseMsg == null) { // No message retrieved. } else { byte[] body = responseMsg.getBody(); // Since getBody() returns a byte array, convert to a string for // the user. String bodyString = new String(body); long deliveryTag = responseMsg.getEnvelope().getDeliveryTag(); writer.println("Message received: " + bodyString); // Acknowledge that we received the message so that the queue // removes the message so that it's not sent to us again. channel.basicAck(deliveryTag, false); } writer.close(); }
From source file:org.hp.samples.RabbitServlet.java
License:Open Source License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(200);//from w ww . ja v a2 s .c o m PrintWriter writer = response.getWriter(); // Create an HTML form for the user to input a message for the queue String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; writer.println(docType + "<html>" + "<body>" + "<p>RabbitMQ for Java</p>" + "<form action='ProcessMessage' method='post'>" + "Message to send: <input type='text' name='message'><br>" + "<input type='submit' value='Send Message'>" + "</form>" + "</body>" + "</html>"); String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello", false, false, false, null); writer.close(); }
From source file:org.iplantcollaborative.ClientRegistrar.java
License:Apache License
public void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.serverConf.getHostname()); factory.setPort(this.serverConf.getPort()); factory.setUsername(this.serverConf.getUserId()); factory.setPassword(this.serverConf.getUserPwd()); factory.setVirtualHost(this.serverConf.getVhostPublish()); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.channel = this.connection.createChannel(); LOG.info("client registrar connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort()); this.channel.basicQos(1); this.channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "#"); this.consumer = new DefaultConsumer(this.channel) { @Override/*from ww w . j a v a 2s .c om*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); LOG.info("registration - " + message); BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); ARequest request = RequestFactory.getRequestInstance(message); // handle lease request if (request instanceof RequestLease) { ResponseLease res = lease((RequestLease) request); String response_json = serializer.toJson(res); if (properties.getReplyTo() != null) { channel.basicPublish("", properties.getReplyTo(), replyProps, response_json.getBytes()); } else { LOG.error("unable to return response. reply_to field is null"); } } else { LOG.error("Unknown request : " + message); } channel.basicAck(envelope.getDeliveryTag(), false); } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { channel.basicConsume(QUEUE_NAME, false, consumer); LOG.info("Waiting for registrations"); } catch (IOException ex) { LOG.error("Exception occurred while consuming message", ex); } } }); this.workerThread.start(); }
From source file:org.iplantcollaborative.DataStoreMessageReceiver.java
License:Apache License
public void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.serverConf.getHostname()); factory.setPort(this.serverConf.getPort()); factory.setUsername(this.serverConf.getUserId()); factory.setPassword(this.serverConf.getUserPwd()); factory.setVirtualHost(this.serverConf.getVhostSubscribe()); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.channel = this.connection.createChannel(); LOG.info("subscriber connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort()); this.channel.basicQos(1); this.queueName = this.channel.queueDeclare().getQueue(); this.channel.queueBind(this.queueName, EXCHANGE_NAME, "#"); this.consumer = new DefaultConsumer(this.channel) { @Override//from www . ja va2s .c o m public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); LOG.debug("subscribe - " + envelope.getRoutingKey() + ":" + message); DataStoreMessageProcessor processor = binder.getProcessor(); if (processor != null) { processor.process(envelope.getRoutingKey(), message); } else { LOG.error("processor not registered"); } channel.basicAck(envelope.getDeliveryTag(), false); } }; this.workerThread = new Thread(new Runnable() { @Override public void run() { try { channel.basicConsume(queueName, consumer); LOG.info("Waiting for messages"); } catch (IOException ex) { LOG.error("Exception occurred while consuming a message", ex); } } }); this.workerThread.start(); }
From source file:org.iplantcollaborative.MessagePublisher.java
License:Apache License
public void connect() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(this.serverConf.getHostname()); factory.setPort(this.serverConf.getPort()); factory.setUsername(this.serverConf.getUserId()); factory.setPassword(this.serverConf.getUserPwd()); factory.setVirtualHost(this.serverConf.getVhostPublish()); factory.setAutomaticRecoveryEnabled(true); this.connection = factory.newConnection(); this.channel = this.connection.createChannel(); this.channel.basicQos(1); LOG.info("publisher connected - " + this.serverConf.getHostname() + ":" + this.serverConf.getPort()); }
From source file:org.jenkinsci.plugins.pushreceiver.RabbitMQConnector.java
License:Apache License
private RabbitMQConnector(String server, String routing) throws InstantiationException { try {/* w ww . jav a2s. c o m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(server); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); if (routing == null || "".equals(routing.trim())) { routing = "#"; } if (!routing.endsWith("#")) { routing = routing + ".#"; } channel.queueBind(queueName, EXCHANGE_NAME, routing); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); running = true; thread = new Thread(this); thread.start(); } catch (IOException e) { LOGGER.severe( "Could not create Rabbit MQ Connection. Please verify server name in the global configuration. " + e); throw new InstantiationException(); } }
From source file:org.mazerunner.core.messaging.Worker.java
License:Apache License
public void doMain(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80);// ww w. ja va 2 s.c o m try { // parse the arguments. parser.parseArgument(args); if (sparkMaster == "" || hadoopHdfs == "") throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>"); ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs); ConfigurationLoader.getInstance().setSparkHost(sparkMaster); ConfigurationLoader.getInstance().setAppName(sparkAppName); ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory); ConfigurationLoader.getInstance().setDriverHost(driverHost); ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost); } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker" + parser.printExample(ALL)); return; } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicQos(20); // Initialize spark context GraphProcessor.initializeSparkContext(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); // Deserialize message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Run PageRank GraphProcessor.processEdgeList(processorMessage); System.out.println(" [x] Done '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }