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:org.axonframework.amqp.eventhandling.RabbitMQBenchmark.java

License:Apache License

private static List<Thread> createChannelSharingThreads(final Connection connection, final String queueName)
        throws IOException {
    List<Thread> threads = new ArrayList<>();
    final Channel localChannel = connection.createChannel();
    for (int i = 0; i < THREAD_COUNT; i++) {
        threads.add(new Thread(() -> {
            try {
                for (int t = 0; t < COMMIT_COUNT; t++) {
                    for (int j = 0; j < COMMIT_SIZE; j++) {
                        localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8"));
                    }/* w  w w  .java2 s .co  m*/
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }));
    }
    return threads;
}

From source file:org.axonframework.amqp.eventhandling.RabbitMQBenchmark.java

License:Apache License

private static List<Thread> createChannelPoolSharingThreads(final Connection connection,
        final String queueName) {
    List<Thread> threads = new ArrayList<>();
    final Queue<Channel> channels = new ArrayBlockingQueue<>(15);
    for (int i = 0; i < THREAD_COUNT; i++) {
        threads.add(new Thread(() -> {
            try {
                for (int t = 0; t < COMMIT_COUNT; t++) {
                    Channel localChannel = channels.poll();
                    if (localChannel == null) {
                        localChannel = connection.createChannel();
                    }/*from   w  ww .j  a v a 2 s .c o m*/
                    localChannel.txSelect();
                    for (int j = 0; j < COMMIT_SIZE; j++) {
                        localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8"));
                    }
                    localChannel.txCommit();
                    if (!channels.offer(localChannel)) {
                        localChannel.close();
                    }
                }
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }));
    }
    return threads;
}

From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java

License:Apache License

private static List<Thread> createChannelCreatingThreads(final Connection connection, final String queueName,
        final boolean transactional) {
    List<Thread> threads = new ArrayList<Thread>();
    for (int i = 0; i < THREAD_COUNT; i++) {
        threads.add(new Thread(new Runnable() {
            @Override/*from   ww  w. jav a2 s .com*/
            public void run() {
                try {
                    for (int t = 0; t < COMMIT_COUNT; t++) {
                        final Channel localChannel = connection.createChannel();
                        if (transactional) {
                            localChannel.txSelect();
                        }
                        for (int j = 0; j < COMMIT_SIZE; j++) {
                            localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8"));
                        }
                        if (transactional) {
                            localChannel.txCommit();
                        }
                        localChannel.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
    return threads;
}

From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java

License:Apache License

private static List<Thread> createChannelSharingThreads(final Connection connection, final String queueName)
        throws IOException {
    List<Thread> threads = new ArrayList<Thread>();
    final Channel localChannel = connection.createChannel();
    for (int i = 0; i < THREAD_COUNT; i++) {
        threads.add(new Thread(new Runnable() {
            @Override/* ww  w . j av a  2  s .  c  om*/
            public void run() {
                try {
                    for (int t = 0; t < COMMIT_COUNT; t++) {
                        for (int j = 0; j < COMMIT_SIZE; j++) {
                            localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8"));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
    return threads;
}

From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java

License:Apache License

private static List<Thread> createChannelPoolSharingThreads(final Connection connection,
        final String queueName) {
    List<Thread> threads = new ArrayList<Thread>();
    final Queue<Channel> channels = new ArrayBlockingQueue<Channel>(15);
    for (int i = 0; i < THREAD_COUNT; i++) {
        threads.add(new Thread(new Runnable() {
            @Override// w  w w .j  a  va  2s . c  o  m
            public void run() {
                try {
                    for (int t = 0; t < COMMIT_COUNT; t++) {
                        Channel localChannel = channels.poll();
                        if (localChannel == null) {
                            localChannel = connection.createChannel();
                        }
                        localChannel.txSelect();
                        for (int j = 0; j < COMMIT_SIZE; j++) {
                            localChannel.basicPublish("", queueName, null, ("message" + t).getBytes("UTF-8"));
                        }
                        localChannel.txCommit();
                        if (!channels.offer(localChannel)) {
                            localChannel.close();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }));
    }
    return threads;
}

From source file:org.ballerinalang.messaging.rabbitmq.util.ChannelUtils.java

License:Open Source License

/**
 * Publishes messages to an exchange.//from w  w  w .j a v  a2s  . c  om
 * Actively declares an non-exclusive, autodelete, non-durable queue if the queue doesn't exist.
 *
 * @param channel    RabbitMQ Channel object.
 * @param routingKey The routing key of the queue.
 * @param message    The message body.
 * @param exchange   The name of the exchange.
 */
public static void basicPublish(Channel channel, String routingKey, byte[] message, String exchange) {
    try {
        channel.basicPublish(exchange, routingKey, null, message);
    } catch (Exception e) {
        String errorMessage = "An error occurred while publishing the message to the queue ";
        throw new RabbitMQConnectorException(errorMessage + e.getMessage(), e);
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQIntegrationTest.java

License:Apache License

private void launchTest(XContentBuilder river, final int numMessages, final int numDocsPerMessage,
        InjectorHook injectorHook, boolean delete, boolean update) throws Exception {

    final String dbName = getDbName();
    logger.info(" --> create index [{}]", dbName);
    try {//from   w  w  w . j a  v  a2 s .com
        client().admin().indices().prepareDelete(dbName).get();
    } catch (IndexMissingException e) {
        // No worries.
    }
    try {
        createIndex(dbName);
    } catch (IndexMissingException e) {
        // No worries.
    }
    ensureGreen(dbName);

    logger.info("  -> Checking rabbitmq running");
    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    Channel channel = null;
    Connection connection = null;
    try {
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(AMQP.PROTOCOL.PORT);
        connection = factory.newConnection();
    } catch (ConnectException ce) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", ce);
    }

    try {
        logger.info("  -> Creating [{}] channel", dbName);
        channel = connection.createChannel();

        logger.info("  -> Creating queue [{}]", dbName);
        channel.queueDeclare(getDbName(), true, false, false, null);

        // We purge the queue in case of something is remaining there
        logger.info("  -> Purging [{}] channel", dbName);
        channel.queuePurge(getDbName());

        logger.info("  -> Put [{}] messages with [{}] documents each = [{}] docs", numMessages,
                numDocsPerMessage, numMessages * numDocsPerMessage);
        final Set<String> removed = new HashSet<String>();
        int nbUpdated = 0;
        for (int i = 0; i < numMessages; i++) {
            StringBuffer message = new StringBuffer();

            for (int j = 0; j < numDocsPerMessage; j++) {
                if (logger.isTraceEnabled()) {
                    logger.trace("  -> Indexing document [{}] - [{}][{}]", i + "_" + j, i, j);
                }
                message.append("{ \"index\" : { \"_index\" : \"" + dbName
                        + "\", \"_type\" : \"typex\", \"_id\" : \"" + i + "_" + j + "\" } }\n");
                message.append("{ \"field\" : \"" + i + "_" + j + "\",\"numeric\" : " + i * j + " }\n");

                // Sometime we update a document
                if (update && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    // We can only update if it has not been removed :)
                    if (!removed.contains(id)) {
                        logger.debug("  -> Updating document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"update\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        message.append(
                                "{ \"doc\": { \"foo\" : \"bar\", \"field2\" : \"" + i + "_" + j + "\" }}\n");
                        nbUpdated++;
                    }
                }

                // Sometime we delete a document
                if (delete && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    if (!removed.contains(id)) {
                        logger.debug("  -> Removing document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"delete\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        removed.add(id);
                    }
                }
            }

            channel.basicPublish("", dbName, null, message.toString().getBytes());
        }

        logger.info("  -> We removed [{}] docs and updated [{}] docs", removed.size(), nbUpdated);

        if (injectorHook != null) {
            logger.info("  -> Injecting extra data");
            injectorHook.inject();
        }

        logger.info(" --> create river");
        IndexResponse indexResponse = index("_river", dbName, "_meta", river);
        assertTrue(indexResponse.isCreated());

        logger.info("-->  checking that river [{}] was created", dbName);
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(true));

        // Check that docs are still processed by the river
        logger.info(" --> waiting for expected number of docs: [{}]",
                numDocsPerMessage * numMessages - removed.size());
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                try {
                    refresh();
                    int expected = numDocsPerMessage * numMessages - removed.size();
                    CountResponse response = client().prepareCount(dbName).get();
                    logger.debug("  -> got {} docs, expected {}", response.getCount(), expected);
                    return response.getCount() == expected;
                } catch (IndexMissingException e) {
                    return false;
                }
            }
        }, 20, TimeUnit.SECONDS), equalTo(true));
    } finally {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
        if (connection != null && connection.isOpen()) {
            connection.close();
        }

        // Deletes the river
        GetResponse response = client().prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status")
                .get();
        if (response.isExists()) {
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_meta").get();
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
        }

        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(false));
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverAsyncTest.java

License:Apache License

@Override
protected void pushMessages(Channel ch) throws IOException {
    String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverBothScriptTest.java

License:Apache License

public static void main(String[] args) throws Exception {
    Settings settings = ImmutableSettings.settingsBuilder().put("gateway.type", "none")
            .put("index.number_of_shards", 1).put("index.number_of_replicas", 0)
            .put("script.native.mock_script.type", MockScriptFactory.class).build();
    Node node = NodeBuilder.nodeBuilder().settings(settings).node();

    node.client().prepareIndex("_river", "test1", "_meta")
            .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("script_filter")
                    .field("script", "ctx.type1.field1 += param1").field("script_lang", "mvel")
                    .startObject("script_params").field("param1", 1).endObject().endObject()
                    .startObject("bulk_script_filter").field("script", "mock_script")
                    .field("script_lang", "native").endObject().endObject())
            .execute().actionGet();//  w w w . ja v a 2 s . co m

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setHost("localhost");
    cfconn.setPort(AMQP.PROTOCOL.PORT);
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();
    ch.exchangeDeclare("elasticsearch", "direct", true);
    ch.queueDeclare("elasticsearch", true, false, false, null);

    String message = "{ \"index\" :  { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n"
            + "{ \"type1\" :  { \"field1\" : 1 } }\n"
            + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"3\" } }\n"
            + "{ \"type1\" :  { \"field1\" : 2 } }" + "";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());

    ch.close();
    conn.close();

    Thread.sleep(10000);
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverHeartbeatTest.java

License:Apache License

public static void main(String[] args) throws Exception {

    Node node = NodeBuilder.nodeBuilder()
            .settings(ImmutableSettings.settingsBuilder().put("gateway.type", "none")).node();

    node.client().prepareIndex("_river", "test1", "_meta").setSource(jsonBuilder().startObject()
            .field("type", "rabbitmq").startObject("rabbitmq").field("heartbeat", "1s").endObject().endObject())
            .execute().actionGet();//from  w  w w.j a va  2s.  c om

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setHost("localhost");
    cfconn.setPort(AMQP.PROTOCOL.PORT);
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();
    ch.exchangeDeclare("elasticsearch", "direct", true);
    ch.queueDeclare("elasticsearch", true, false, false, null);

    String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());

    ch.close();
    conn.close();

    Thread.sleep(100000);
}