Example usage for com.rabbitmq.client Channel basicPublish

List of usage examples for com.rabbitmq.client Channel basicPublish

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel basicPublish.

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;
    try {//  ww  w  . j  av  a 2 s.  c  o  m
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        logger.info("send message = {}", message);
        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}

From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMulitMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;
    try {/*w  w  w. j av a2s  . co m*/
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        int i = 0;
        int loop = 0;
        String originalMessage = message;
        while (loop < 10000) {
            loop++;
            message += i++;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            logger.info("send message = {}", message);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            message = originalMessage;
        }

        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}

From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java

License:Apache License

@Override
public void submitTask(AsyncExecutionRequest request) throws AsyncTaskSubmissionException {
    try {/*  ww  w.j av a2s.  com*/
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicPublish(this.exchange, this.routingKey, null, serialize(request));
    } catch (IOException | TimeoutException ex) {
        LOGGER.error("Failed to submit action execution request", ex);
        throw new AsyncTaskSubmissionException();
    }
}

From source file:com.github.liyp.rabbitmq.demo2.Producer.java

License:Apache License

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("liyp");
    factory.setPassword("liyp");
    factory.setVirtualHost("/");
    factory.setHost("127.0.0.1");
    factory.setPort(5672);//from w  w w  .ja  va2s. co m
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    for (int i = 0; i < 10000; i++) {
        byte[] messageBodyBytes = "Hello, world!".getBytes();
        channel.basicPublish("", "my-queue", null, messageBodyBytes);
        System.out.println(channel.isOpen());
    }

    channel.close();
    conn.close();
}

From source file:com.github.liyp.rabbitmq.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {//from   w ww  .j  a  v a  2  s  . c o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

        System.out.println(" [x] Awaiting RPC requests");

        while (true) {
            String response = null;

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                int n = Integer.parseInt(message);

                System.out.println(" [.] fib(" + message + ")");
                response = "" + fib(n);
            } catch (Exception e) {
                System.out.println(" [.] " + e.toString());
                response = "";
            } finally {
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));

                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:com.googlecode.jmxtrans.model.output.RabbitMQWriter.java

License:Open Source License

@Override
protected void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
    // Iterating through the list of query results
    Channel pubChan = createChannel();

    for (Result result : results) {
        Map<String, Object> resultValues = result.getValues();
        for (Map.Entry<String, Object> values : resultValues.entrySet()) {
        }/* ww w.  j  av a2s  .  c  o  m*/
    }
    String msg = createJsonMessage(query, results);
    String rk = server.getAlias() + "." + query.getResultAlias();
    pubChan.basicPublish("amq.topic", rk, null, msg.getBytes());
}

From source file:com.grnet.parsers.Worker.java

License:Open Source License

@Override
public void run() {
    // TODO Auto-generated method stub

    String name = xml.getName();// w w  w . j a  v  a 2  s  .c o  m
    Document document;
    try {
        SAXBuilder builder = new SAXBuilder();
        document = (Document) builder.build(xml);

        Element rootNode = document.getRootElement();
        Record record = new Record();

        record.setMetadata(rootNode);

        String elementsString = properties.getProperty(Constants.elements);
        String[] elements = elementsString.split(",");

        for (int i = 0; i < elements.length; i++) {

            List<Element> elementList = JDomUtils.getXpathList(elements[i],
                    Namespace.getNamespace(properties.getProperty(Constants.prefix),
                            properties.getProperty(Constants.uri)),
                    record.getMetadata());

            if (elementList != null) {

                for (int j = 0; j < elementList.size(); j++) {
                    Element elmt = elementList.get(j);
                    String titleText = elmt.getText();

                    if (!titleText.equals("")) {

                        Attribute langAtt = elmt.getAttribute(properties.getProperty(Constants.attName));

                        String chosenLangAtt = properties.getProperty(Constants.attName);

                        if (langAtt == null || langAtt.getValue().equals("")
                                || langAtt.getValue().equals("none")) {
                            StringBuffer logstring = new StringBuffer();
                            try {
                                Detector detector = DetectorFactory.create();
                                detector.append(titleText);
                                String lang = detector.detect();

                                Attribute attribute = new Attribute(chosenLangAtt, lang);
                                elmt.setAttribute(attribute);

                                stats.raiseElementsLangDetected();

                                logstring.append(xml.getParentFile().getName());
                                logstring.append(" " + name.substring(0, name.lastIndexOf(".")));

                                logstring.append(" " + elements[i]);
                                logstring.append(" " + lang);

                                slf4jLogger.info(logstring.toString());

                                System.out.println("Opening queue connection...");
                                Connection connection = this.factory.newConnection();
                                Channel channel = connection.createChannel();
                                channel.queueDeclare(this.queue, false, false, false, null);

                                channel.basicPublish("", this.queue, null, logstring.toString().getBytes());

                                channel.close();
                                connection.close();
                                System.out.println("Opening queue connection...");

                                stats.addElementD(elements[i]);
                                flag = true;
                            } catch (LangDetectException e) {
                                // TODO Auto-generated catch block
                                // e.printStackTrace();
                                logstring.append(xml.getParentFile().getName());
                                logstring.append(" " + name.substring(0, name.lastIndexOf(".")));
                                logstring.append(" " + "NoLangDetected");
                                slf4jLogger.info(logstring.toString());

                                Connection connection = this.factory.newConnection();
                                Channel channel = connection.createChannel();
                                channel.queueDeclare(this.queue, false, false, false, null);

                                channel.basicPublish("", this.queue, null, logstring.toString().getBytes());

                                channel.close();
                                connection.close();

                                if (strict.equals("true"))
                                    recon = false;
                                else {
                                    recon = true;
                                    continue;
                                }
                            }
                        }

                    }

                }

            }

        }

        if (recon) {
            String xmlString = JDomUtils.parseXml2string(record.getMetadata().getDocument(), null);

            OaiUtils.writeStringToFileInEncodingUTF8(xmlString, outputPath + File.separator + name);
        } else {
            String xmlString = JDomUtils.parseXml2string(record.getMetadata().getDocument(), null);

            OaiUtils.writeStringToFileInEncodingUTF8(xmlString, bad + File.separator + name);
        }
        if (flag)
            stats.raiseFilesLangDetected();

        if (recon == false)
            stats.raiseFilessLangNotDetected();

    } catch (JDOMException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

From source file:com.groupx.recipientlist.test.RecipientList.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();//from w  w w .  ja v a 2 s  .c o  m
    connection.close();
}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static String sendConfig1(String who, String config) throws Exception {

    /* calling connectionFactory to create a custome connexion with
    * rabbitMQ server information.//ww w.ja v a  2 s .co m
    */
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);
    System.out.println("connection ok");
    // establish the connection with RabbitMQ server using our factory.
    Connection connection = factory.newConnection();
    // System.out.println("connection ok1");
    // We're connected now, to the broker on the cloud machine.
    // If we wanted to connect to a broker on a the local machine we'd simply specify "localhost" as IP adresse.
    // creating a "configuration" direct channel/queue
    Channel channel = connection.createChannel();
    //  System.out.println("connection ok2");
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    //  System.out.println("exchangeDeclare");
    // the message and the distination
    String forWho = who;
    String message = config;

    // publish the message
    channel.basicPublish(EXCHANGE_NAME, forWho, null, message.getBytes());
    //  System.out.println("basicPublish");
    // close the queue and the connexion
    channel.close();
    connection.close();
    return " [x] Sent '" + forWho + "':'" + message + "'";
}

From source file:com.jbrisbin.groovy.mqdsl.PublishClosure.java

License:Apache License

@Override
public Object call(Object[] args) {
    if (args.length < 2) {
        return null;
    }//w w w.java2s.c  om

    String exchange = args[0].toString();
    String routingKey = args[1].toString();
    Map headers = null;
    byte[] body = null;
    for (int i = 2; i < args.length; i++) {
        if (args[i] instanceof Map) {
            headers = (Map) args[i];
        } else if (args[i] instanceof byte[]) {
            body = (byte[]) args[i];
        } else if (args[i] instanceof String || args[i] instanceof GString) {
            body = args[i].toString().getBytes();
        }
    }

    AMQP.BasicProperties properties = new AMQP.BasicProperties();
    if (null != headers) {
        if (headers.containsKey("contentType")) {
            properties.setContentType(headers.remove("contentType").toString());
        }
        if (headers.containsKey("correlationId")) {
            properties.setCorrelationId(headers.remove("correlationId").toString());
        }
        if (headers.containsKey("replyTo")) {
            properties.setReplyTo(headers.remove("replyTo").toString());
        }
        if (headers.containsKey("contentEncoding")) {
            properties.setContentEncoding(headers.remove("contentEncoding").toString());
        }
        properties.setHeaders(headers);
    }

    try {
        Channel channel = connection.createChannel();
        channel.basicPublish(exchange, routingKey, properties, body);
        channel.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return this;
}