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:Colas.Colas.java

private String reciver(String enviar) {
    try {/*  w w  w . j a va 2 s. c  o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP);
        factory.setPort(5672);
        factory.setUsername("valencia");
        factory.setPassword("admin123");

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

        channel.queueDeclare("SC", false, false, false, null);

        channel.basicPublish("", "SC", null, enviar.getBytes());
        System.out.println(" [x] Sent '" + enviar + "'");
        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error enviando ");
        e.printStackTrace();
    }
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("admin123");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("CF", false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("CF", true, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
            return message;

        }
    } catch (Exception e) {
        System.out.println("Error reciviendo ");
        e.printStackTrace();
    }
    return "Error";

}

From source file:Colas.Colas.java

private void sender(String string) {
    try {/*from  w  ww  .j av  a 2 s  .  c  o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("valencia");
        factory.setPassword("admin123");

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

        channel.queueDeclare("SC", false, false, false, null);

        channel.basicPublish("", "SC", null, string.getBytes());
        System.out.println(" [x] Sent '" + string + "'");
        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error enviando ");
        e.printStackTrace();
    }
}

From source file:com.abiquo.commons.amqp.util.ProducerUtils.java

License:Open Source License

/**
 * Publish a message NonMandatory and NonImmediate.
 * /*ww w .  jav a2 s. co  m*/
 * @param channel The AMQ Channel to use.
 * @param exchange The exchange to publish the message to
 * @param routingKey The routing key
 * @param body The message, not null!
 * @throws IOException If an error is encountered
 */
public static void publishPersistentText(Channel channel, String exchange, String routingKey, byte[] body)
        throws IOException {
    channel.basicPublish(exchange, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, body);
}

From source file:com.akash.sparktutorial.AppClass.java

public static void main(String[] args) throws Exception {
    port(3990);/*from   w ww .  j  av a2s. com*/
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    com.rabbitmq.client.Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    final String QUEUE_NAME = "hello";

    // test route for heroku
    get("/default/:name", (req, res) -> {
        return "Hello " + req.params(":name") + " from heroku";
    });

    //sample route
    get("/hello/:name", (req, res) -> {
        channel.basicPublish("", QUEUE_NAME, null, "hello world".getBytes()); //test
        System.out.println("[x] Sent"); //test
        return "Hello:" + req.params(":name") + "\n New message publishes to RabbitMQ";
    });

    //route to take in the dashboard requets
    post("/request", (req, res) -> {
        String payload = null;
        if (req.contentType().equals("application/json")) {
            //payload in proper format, send request as message to rabbit
            payload = req.body();
            channel.basicPublish("", QUEUE_NAME, null, payload.getBytes());
        } else {
            //payload in incorrect format, send response error
        }
        System.out.println(req.contentType() + "\n" + payload);
        return "hello";
    });
}

From source file:com.anteam.demo.rabbitmq.RabbitMQProducer.java

License:Apache License

public static void main(String[] args) throws java.io.IOException {

    // /*w w  w  . j  av  a 2  s. co  m*/
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    // 
    Connection connection = factory.newConnection();

    // ??
    Channel channel = connection.createChannel();

    // ?
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    String message = "Hello World!";

    // ???Exchange??""?
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

    System.out.println(" [x] Sent '" + message + "'");

    // ??
    channel.close();
    connection.close();

}

From source file:com.anton.dev.tqrb.MessageProducer.java

public static void main(String[] args) throws IOException, TimeoutException {

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

    channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    String message = "Hola!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Enviar '" + message + "'");
    channel.close();/*from  www .ja  v  a2 s  . co m*/
    connection.close();
}

From source file:com.att.cspd.SimpleSipServlet.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w ww  .ja  va  2  s  .  c  om*/
 */
protected void doNotify(SipServletRequest request) throws ServletException, IOException {

    Channel channel = null;
    String routingKey = "";

    //a trick to change routingKey value.
    //routingKey = getBindingKey();

    try {

        channel = pool.borrowObject();
        String message = request.getCallId();
        logger.info("doNotify method: Request dump: " + request.toString());
        Iterator itr = request.getHeaderNames();
        while (itr.hasNext()) {
            logger.info("Header Name : " + itr.next() + "\n");
        }
        String toHdr = request.getHeader("To");

        Matcher matcher = Pattern.compile("sip:(.*)@.+").matcher(toHdr);
        if (matcher.find()) {
            String userpart = matcher.group(1);
            logger.info("user part of the sip url : " + userpart);
            routingKey = userpart;
        }

        channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
        channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
        logger.info("PUBLISH A MESSAGE : " + message);

        logger.info("*************************************");
        logger.info("**" + "Number active : " + pool.getNumActive() + " ***");
        logger.info("**" + "Number idle  : " + pool.getNumIdle() + " ***");
        logger.info("*************************************");

    } catch (NoSuchElementException e) {

        logger.error(e.getMessage());
        throw new ServletException(e);

    } catch (IllegalStateException e) {

        logger.error(e.getMessage());
        throw new ServletException(e);
    } catch (Exception e) {

        logger.error(e.getMessage());
        throw new ServletException(e);
    } finally {
        if (channel != null) {
            try {
                pool.returnObject(channel);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("Failed to return channel back to pool. Exception message: " + e.getMessage());
            }
            //logger.info("RETURN CHANNEL TO THE POOL");
        }

    }
    SipServletResponse sipServletResponse = request.createResponse(SipServletResponse.SC_OK);
    sipServletResponse.send();

}

From source file:com.audaexplore.b2b.GenAddFnol.java

private void publishFnol(List<Fnol> fnolList) {
    String amqpURI = null;//from   ww  w.j  a v a  2  s . c om
    ConnectionFactory factory = null;
    Channel channel = null;
    Connection connection = null;
    String message;
    String BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
    Map<String, String> env = System.getenv();
    String boundServicesJson = env.get(BOUND_SERVICES_ENV_VARIABLE_NAME);
    //String boundServicesJson="{\"staging_env_json\":{},\"running_env_json\":{},\"system_env_json\":{\"VCAP_SERVICES\":{\"cloudamqp\":[{\"name\":\"MQRabbit\",\"label\":\"cloudamqp\",\"tags\":[\"Web-based\",\"UserProvisioning\",\"MessagingandQueuing\",\"amqp\",\"Backup\",\"SingleSign-On\",\"NewProduct\",\"rabbitmq\",\"CertifiedApplications\",\"Android\",\"DeveloperTools\",\"DevelopmentandTestTools\",\"Buyable\",\"Messaging\",\"Importable\",\"ITManagement\"],\"plan\":\"lemur\",\"credentials\":{\"uri\":\"amqp://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/kujcbqju\",\"http_api_uri\":\"https://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/api/\"}}],\"newrelic\":[{\"name\":\"NewRelic\",\"label\":\"newrelic\",\"tags\":[\"Monitoring\"],\"plan\":\"standard\",\"credentials\":{\"licenseKey\":\"a8a96a124d1b58d708a2c4c07c6cff8938e2e2f4\"}}],\"mongolab\":[{\"name\":\"MongoDB\",\"label\":\"mongolab\",\"tags\":[\"DataStore\",\"document\",\"mongodb\"],\"plan\":\"sandbox\",\"credentials\":{\"uri\":\"mongodb://CloudFoundry_31lvrquo_j44bi0vu_3gjp7i4s:6RAtFVBfQUCe_DV7LAq5uCffOXaEXdly@ds047315.mongolab.com:47315/CloudFoundry_31lvrquo_j44bi0vu\"}}]}},\"application_env_json\":{\"VCAP_APPLICATION\":{\"limits\":{\"mem\":512,\"disk\":1024,\"fds\":16384},\"application_id\":\"87bdc475-83c4-4df9-92d1-40ff9bf82249\",\"application_version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"application_name\":\"vinservice\",\"application_uris\":[\"vinservice.cfapps.io\"],\"version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"name\":\"vinservice\",\"space_name\":\"development\",\"space_id\":\"d33d438c-860a-46d3-ab33-4c2efac841be\",\"uris\":[\"vinservice.cfapps.io\"],\"users\":null}}}";

    if (StringUtils.isNotBlank(boundServicesJson)) {
        //amqpURI =  JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri",String.class);
        JSONArray jsonArray = JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri");
        amqpURI = jsonArray.get(0).toString();
    } else {
        amqpURI = "amqp://localhost";
    }

    System.out.println("Sending messages to " + amqpURI);
    //System.exit(0);

    try {
        factory = new ConnectionFactory();
        factory.setUri(amqpURI);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("fnol", true, false, false, null);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (TimeoutException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    for (Fnol fnol : fnolList) {
        message = new Gson().toJson(fnol);

        try {
            channel.basicPublish("amq.direct", "fnolKey",
                    new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).build(),
                    //MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            System.out.println("message " + message + " was published");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.audaexplore.b2b.GenAddFnol.java

private void publishCars(List<Car> carList) {
    String amqpURI = null;//  ww w. j  a v  a  2  s . co  m
    ConnectionFactory factory = null;
    Channel channel = null;
    Connection connection = null;
    String message;
    String BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
    Map<String, String> env = System.getenv();
    String boundServicesJson = env.get(BOUND_SERVICES_ENV_VARIABLE_NAME);
    //String boundServicesJson="{\"staging_env_json\":{},\"running_env_json\":{},\"system_env_json\":{\"VCAP_SERVICES\":{\"cloudamqp\":[{\"name\":\"MQRabbit\",\"label\":\"cloudamqp\",\"tags\":[\"Web-based\",\"UserProvisioning\",\"MessagingandQueuing\",\"amqp\",\"Backup\",\"SingleSign-On\",\"NewProduct\",\"rabbitmq\",\"CertifiedApplications\",\"Android\",\"DeveloperTools\",\"DevelopmentandTestTools\",\"Buyable\",\"Messaging\",\"Importable\",\"ITManagement\"],\"plan\":\"lemur\",\"credentials\":{\"uri\":\"amqp://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/kujcbqju\",\"http_api_uri\":\"https://kujcbqju:xr-HKmBcq5Lv87CCrYlQ6NaVmunhU8cv@moose.rmq.cloudamqp.com/api/\"}}],\"newrelic\":[{\"name\":\"NewRelic\",\"label\":\"newrelic\",\"tags\":[\"Monitoring\"],\"plan\":\"standard\",\"credentials\":{\"licenseKey\":\"a8a96a124d1b58d708a2c4c07c6cff8938e2e2f4\"}}],\"mongolab\":[{\"name\":\"MongoDB\",\"label\":\"mongolab\",\"tags\":[\"DataStore\",\"document\",\"mongodb\"],\"plan\":\"sandbox\",\"credentials\":{\"uri\":\"mongodb://CloudFoundry_31lvrquo_j44bi0vu_3gjp7i4s:6RAtFVBfQUCe_DV7LAq5uCffOXaEXdly@ds047315.mongolab.com:47315/CloudFoundry_31lvrquo_j44bi0vu\"}}]}},\"application_env_json\":{\"VCAP_APPLICATION\":{\"limits\":{\"mem\":512,\"disk\":1024,\"fds\":16384},\"application_id\":\"87bdc475-83c4-4df9-92d1-40ff9bf82249\",\"application_version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"application_name\":\"vinservice\",\"application_uris\":[\"vinservice.cfapps.io\"],\"version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"name\":\"vinservice\",\"space_name\":\"development\",\"space_id\":\"d33d438c-860a-46d3-ab33-4c2efac841be\",\"uris\":[\"vinservice.cfapps.io\"],\"users\":null}}}";

    if (StringUtils.isNotBlank(boundServicesJson)) {
        //amqpURI =  JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri",String.class);
        JSONArray jsonArray = JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri");
        amqpURI = jsonArray.get(0).toString();
    } else {
        amqpURI = "amqp://localhost";
    }

    System.out.println("Sending messages to " + amqpURI);
    //System.exit(0);

    try {
        factory = new ConnectionFactory();
        factory.setUri(amqpURI);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("fnol", true, false, false, null);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (TimeoutException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (KeyManagementException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    for (Car car : carList) {
        message = new Gson().toJson(car);

        try {
            channel.basicPublish("amq.direct", "fnolKey",
                    new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).build(),
                    //MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.getBytes());
            System.out.println("message " + message + " was published");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        channel.close();
        connection.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.colm.app.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Connection connection;//  w  ww . j a  v  a 2s.  co m
    Channel channel;
    String replyQueueName;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.0.13");
    factory.setPassword("admin");
    factory.setUsername("admin");
    factory.setVirtualHost("admin");
    connection = factory.newConnection();
    channel = connection.createChannel();
    String queneNAme = "rabbitmq_test";
    channel.queueDeclare(queneNAme, false, false, false, null);
    String message = "Something Else";
    for (int i = 0; i < 1000; i++) {
        channel.basicPublish("", queneNAme, null, message.getBytes());
    }
    System.out.println("Sent '" + message + "'");
    channel.close();
    connection.close();

}