List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSamplePublisher.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException, TimeoutException { if (argv.length > 0) { TASK_QUEUE_NAME = argv[0];/*from w w w . j ava 2s .c o m*/ } ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); String data = ""; try { BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt // read file line by line String line; Scanner scanner; int count = 0; while ((line = reader.readLine()) != null) { scanner = new Scanner(line); while (scanner.hasNext()) { String dataInLine = scanner.next(); if (dataInLine.contains("----")) { if (data.length() > 100) { for (int i = 0; i < 5; i++) { count++; System.out.println(count); // System.out.println(data); //Thread.sleep(5000); String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_", "_" + i + "_"); channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, data1.getBytes()); } } data = ""; } else { data += " " + dataInLine; if (dataInLine.contains(".") && !dataInLine.contains("<")) { data += "\n"; } } } } } catch (Exception e) { e.printStackTrace(); } channel.close(); connection.close(); }
From source file:other.common.messaging.JsonConnection.java
License:Apache License
public JsonConnection() { // Create a ConnectionFactory ConnectionFactory connectionFactory = new ConnectionFactory(); // Create a Connection try {/*from w w w . jav a2 s . c o m*/ // Create a ConnectionFactory connectionFactory.setHost(Play.configuration.getProperty("AMQPhost")); connectionFactory.setPort(Integer.valueOf(Play.configuration.getProperty("AMQPport"))); connectionFactory.setUsername(Play.configuration.getProperty("AMQPuser")); connectionFactory.setPassword(Play.configuration.getProperty("AMQPpasswd")); /* The AMQ connection. */ Connection connection = connectionFactory.newConnection(); channel = connection.createChannel(); // Create exchange channel.exchangeDeclare("iris", "topic", true); } catch (IOException e) { LOGGER.error("Error while connection to AMQP broker: " + e.getMessage()); System.exit(1); } }
From source file:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java
License:Open Source License
/** * Creates channel./*from w ww. j av a 2 s . c om*/ * * @param connection Connection to Rabbit MQ server. * @throws BusException Any problem will rise the exception. */ public static Channel createChannel(Connection connection) throws BusException { try { return connection.createChannel(); } catch (IOException e) { throw new BusException("Can not create channel.", e); } }
From source file:pl.nask.hsn2.bus.test.rabbitmq.RbtConsumeEndPointTest.java
License:Open Source License
@Test(enabled = testEnabler) public void consumeTest() throws IOException, BusException, InterruptedException, TimeoutException { int numberOfMessages = 1000; final Connection connection = getConnection(20); // removing previous messages RbtUtils.purgeQueue(connection.createChannel(), this.destination); final AtomicInteger num = new AtomicInteger(0); ConsumeEndPointHandler handler = new ConsumeEndPointHandler() { final Random randomGenerator = new Random(); @Override//from w w w . j a v a 2 s. c om public void handleMessage(Message message) { LOGGER.info("Got message: type={}", message.getType()); num.incrementAndGet(); int wait = randomGenerator.nextInt(10); LOGGER.info("Random wait is {} secs.", wait); try { Thread.sleep(1000 * wait); } catch (InterruptedException e) { e.printStackTrace(); } } }; // produce 1000 messages FireAndForgetEndPoint nEp = new PooledFireAndForgetEndPoint( new PooledFireAndForgetEndPoint.PooledNEPCreateCallback() { @Override public FireAndForgetEndPoint create() { try { return new RbtFireAndForgetEndPoint(connection); } catch (BusException e) { throw new RuntimeException(e); } } }); for (int i = 0; i < numberOfMessages; i++) { Message message = new Message("SomeType " + i, "".getBytes(), new Destination("serviceQueue")); nEp.sendNotify(message); LOGGER.info("Producing message: type={}", message.getType()); } LOGGER.info("Test messages produced."); ConsumeEndPoint endPoint = new RbtConsumeEndPoint(connection, handler, "serviceQueue", false, 10); long startTime = System.currentTimeMillis(); while (num.get() < 1000 && (System.currentTimeMillis() - startTime < 1500000)) { Thread.sleep(10); } endPoint.close(); LOGGER.info("Processed {} messags", num.get()); Assert.assertEquals(num.get(), numberOfMessages); }
From source file:play.modules.rabbitmq.RabbitMQPlugin.java
License:Apache License
/** * Gets the task channel.// ww w.j a v a2 s .c o m * * @return the task channel */ protected Channel createChannel() { Channel channel = null; int attempts = 0; while (true) { attempts++; Logger.info("Attempting to connect to queue: attempt " + attempts); try { Connection connection = this.getConnection(); channel = connection.createChannel(); break; } catch (IOException e) { Logger.error("Error creating RabbitMQ channel, retrying in 5 secs - Exception: %s", ExceptionUtil.getStackTrace(e)); try { Thread.sleep(1000 * 5); } catch (InterruptedException ex) { } } } return channel; }
From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.QueryConsumer.java
License:Apache License
public void run() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); final Session session = cluster.connect(); session.execute(String.format("CREATE TABLE IF NOT EXISTS tester.warningsrdd (ssn text, " + "batchStartTime bigint, id uuid, amount decimal, rule text, PRIMARY KEY(batchStartTime, id))")); final PreparedStatement preparedStatement = session .prepare("SELECT * FROM tester.warningsrdd where batchStartTime = ?"); try {/*from ww w. j a va 2s. c om*/ Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); final String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue, EXCHANGE_NAME, ""); final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body); long batchStartTime = Long.parseLong(message); System.out.println("Writing batch with start time of " + new Date(batchStartTime)); ResultSet warningsResultSet = session.execute(preparedStatement.bind(batchStartTime)); int count = 0; for (Row warning : warningsResultSet) { count += 1; BigDecimal decimal = warning.getDecimal("amount"); UUID id = warning.getUUID("id"); String ssn = warning.getString("ssn"); String rule = warning.getString("rule"); Warning warningObj = new Warning(); warningObj.setAmount(decimal); warningObj.setId(id); warningObj.setSsn(ssn); warningObj.setRule(rule); notifyUI(warningObj); } System.out.println("Batch with start time of " + new Date(batchStartTime) + " Complete with " + count + " items."); } }; channel.basicConsume(queue, true, consumer); } catch (IOException e) { e.printStackTrace(); } }
From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.ResponseWriter.java
License:Apache License
private Messenger initRabbitMqResponseQueue() { ConnectionFactory factory = new ConnectionFactory(); final Connection connection; final Channel channel; factory.setHost("localhost"); try {/*ww w . j av a 2 s . co m*/ connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); } catch (IOException e) { throw new RuntimeException(e); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { ResponseWriter.mainThread.interrupt(); try { channel.close(); connection.close(); } catch (IOException e) { e.printStackTrace(); } } }); return new MessengerImpl(channel); }
From source file:pro.foundev.examples.spark_streaming.java.interactive.smartconsumer.DeduplicatingRabbitMQConsumer.java
License:Apache License
public void run() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try {//from w w w .j a va 2s . c o m Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(EXCHANGE_NAME, true, consumer); Set<String> messages = new HashSet<>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); messages.add(message); if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 1000l) { System.out.println("it should be safe to submit messages now"); for (String m : messages) { //notifying user interface System.out.println(m); } stopwatch.stop(); stopwatch.reset(); messages.clear(); } if (messages.size() > 100000000) { System.out.println("save off to file system and clear before we lose everything"); messages.clear(); } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQEmitWarnings.java
License:Apache License
public static void main(String[] argv) throws java.io.IOException { String master = Args.parseMaster(argv); mainThread = Thread.currentThread(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(master);/* ww w. ja v a2 s.c om*/ final Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { RabbitMQEmitWarnings.mainThread.interrupt(); try { channel.close(); connection.close(); } catch (IOException e) { e.printStackTrace(); } } }); while (true) { String message = buildMessage(); channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:pt.ua.ies.Main.java
public static void main(String[] args) { try {// w w w . j a v a 2 s. c om ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String message = "Random Message " + new Random().nextInt(1000); channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); /** * Close the channel and the connection */ channel.close(); connection.close(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }