Search in sources :

Example 6 with Publication

use of io.aeron.Publication in project Aeron by real-logic.

the class SimplePublisher method main.

public static void main(final String[] args) throws Exception {
    // Allocate enough buffer size to hold maximum message length
    // The UnsafeBuffer class is part of the Agrona library and is used for efficient buffer management
    final UnsafeBuffer buffer = new UnsafeBuffer(BufferUtil.allocateDirectAligned(512, BitUtil.CACHE_LINE_LENGTH));
    // The channel (an endpoint identifier) to send the message to
    final String channel = "aeron:udp?endpoint=localhost:40123";
    // A unique identifier for a stream within a channel. Stream ID 0 is reserved
    // for internal use and should not be used by applications.
    final int streamId = 10;
    System.out.println("Publishing to " + channel + " on stream Id " + streamId);
    // Create a context, needed for client connection to media driver
    // A separate media driver process needs to be running prior to starting this application
    final Aeron.Context ctx = new Aeron.Context();
    // AutoCloseable, and will automatically clean up resources when this try block is finished.
    try (Aeron aeron = Aeron.connect(ctx);
        Publication publication = aeron.addPublication(channel, streamId)) {
        final String message = "Hello World! ";
        final byte[] messageBytes = message.getBytes();
        buffer.putBytes(0, messageBytes);
        // Try to publish the buffer. 'offer' is a non-blocking call.
        // If it returns less than 0, the message was not sent, and the offer should be retried.
        final long result = publication.offer(buffer, 0, messageBytes.length);
        if (result < 0L) {
            if (result == Publication.BACK_PRESSURED) {
                System.out.println(" Offer failed due to back pressure");
            } else if (result == Publication.NOT_CONNECTED) {
                System.out.println(" Offer failed because publisher is not connected to subscriber");
            } else if (result == Publication.ADMIN_ACTION) {
                System.out.println("Offer failed because of an administration action in the system");
            } else if (result == Publication.CLOSED) {
                System.out.println("Offer failed publication is closed");
            } else {
                System.out.println(" Offer failed due to unknown reason");
            }
        } else {
            System.out.println(" yay !!");
        }
        System.out.println("Done sending.");
    }
}
Also used : Publication(io.aeron.Publication) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) Aeron(io.aeron.Aeron)

Example 7 with Publication

use of io.aeron.Publication in project Aeron by real-logic.

the class ArchiverProtocolProxy method sendNotification.

private void sendNotification(final int length) {
    final Publication publication = this.archiverNotifications;
    while (true) {
        final long result = publication.offer(outboundBuffer, 0, MessageHeaderEncoder.ENCODED_LENGTH + length);
        if (result > 0 || result == Publication.NOT_CONNECTED) {
            idleStrategy.reset();
            break;
        } else if (result == Publication.CLOSED) {
            throw new IllegalStateException();
        }
        idleStrategy.idle();
    }
}
Also used : Publication(io.aeron.Publication)

Example 8 with Publication

use of io.aeron.Publication in project Aeron by real-logic.

the class StreamingPublisher method main.

public static void main(final String[] args) throws Exception {
    if (MESSAGE_LENGTH < SIZE_OF_LONG) {
        throw new IllegalArgumentException(String.format("Message length must be at least %d bytes", SIZE_OF_LONG));
    }
    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context context = new Aeron.Context();
    if (EMBEDDED_MEDIA_DRIVER) {
        context.aeronDirectoryName(driver.aeronDirectoryName());
    }
    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), StreamingPublisher::printRate);
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(reporter);
    // clean up resources when this try block is finished.
    try (Aeron aeron = Aeron.connect(context);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID)) {
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        do {
            printingActive = true;
            System.out.format("%nStreaming %,d messages of%s size %d bytes to %s on stream Id %d%n", NUMBER_OF_MESSAGES, (RANDOM_MESSAGE_LENGTH) ? " random" : "", MESSAGE_LENGTH, CHANNEL, STREAM_ID);
            long backPressureCount = 0;
            for (long i = 0; i < NUMBER_OF_MESSAGES; i++) {
                final int length = LENGTH_GENERATOR.getAsInt();
                ATOMIC_BUFFER.putLong(0, i);
                OFFER_IDLE_STRATEGY.reset();
                while (publication.offer(ATOMIC_BUFFER, 0, length) < 0L) {
                    // The offer failed, which is usually due to the publication
                    // being temporarily blocked.  Retry the offer after a short
                    // spin/yield/sleep, depending on the chosen IdleStrategy.
                    backPressureCount++;
                    OFFER_IDLE_STRATEGY.idle();
                }
                reporter.onMessage(1, length);
            }
            System.out.println("Done streaming. Back pressure ratio " + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (0 < LINGER_TIMEOUT_MS) {
                System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
                Thread.sleep(LINGER_TIMEOUT_MS);
            }
            printingActive = false;
        } while (barrier.await());
    }
    reporter.halt();
    executor.shutdown();
    CloseHelper.quietClose(driver);
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) ExecutorService(java.util.concurrent.ExecutorService) Publication(io.aeron.Publication) ContinueBarrier(org.agrona.console.ContinueBarrier) Aeron(io.aeron.Aeron)

Example 9 with Publication

use of io.aeron.Publication in project Aeron by real-logic.

the class EmbeddedThroughput method main.

public static void main(final String[] args) throws Exception {
    MediaDriver.loadPropertiesFiles(args);
    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), EmbeddedThroughput::printRate);
    final FragmentHandler rateReporterHandler = rateReporterHandler(reporter);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final Aeron.Context context = new Aeron.Context();
    final AtomicBoolean running = new AtomicBoolean(true);
    try (MediaDriver ignore = MediaDriver.launch();
        Aeron aeron = Aeron.connect(context);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID);
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID)) {
        executor.execute(reporter);
        executor.execute(() -> SamplesUtil.subscriberLoop(rateReporterHandler, FRAGMENT_COUNT_LIMIT, running).accept(subscription));
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        do {
            System.out.format("%nStreaming %,d messages of size %d bytes to %s on stream Id %d%n", NUMBER_OF_MESSAGES, MESSAGE_LENGTH, CHANNEL, STREAM_ID);
            printingActive = true;
            long backPressureCount = 0;
            for (long i = 0; i < NUMBER_OF_MESSAGES; i++) {
                ATOMIC_BUFFER.putLong(0, i);
                OFFER_IDLE_STRATEGY.reset();
                while (publication.offer(ATOMIC_BUFFER, 0, ATOMIC_BUFFER.capacity()) < 0) {
                    OFFER_IDLE_STRATEGY.idle();
                    backPressureCount++;
                }
            }
            System.out.println("Done streaming. backPressureRatio=" + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (0 < LINGER_TIMEOUT_MS) {
                System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
                Thread.sleep(LINGER_TIMEOUT_MS);
            }
            printingActive = false;
        } while (barrier.await());
        running.set(false);
        reporter.halt();
        executor.shutdown();
    }
}
Also used : Publication(io.aeron.Publication) ContinueBarrier(org.agrona.console.ContinueBarrier) Aeron(io.aeron.Aeron) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) FragmentHandler(io.aeron.logbuffer.FragmentHandler) ExecutorService(java.util.concurrent.ExecutorService) Subscription(io.aeron.Subscription)

Aggregations

Publication (io.aeron.Publication)9 Aeron (io.aeron.Aeron)8 Subscription (io.aeron.Subscription)4 MediaDriver (io.aeron.driver.MediaDriver)4 FragmentAssembler (io.aeron.FragmentAssembler)3 ContinueBarrier (org.agrona.console.ContinueBarrier)3 ExecutorService (java.util.concurrent.ExecutorService)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 FragmentHandler (io.aeron.logbuffer.FragmentHandler)1 BusySpinIdleStrategy (org.agrona.concurrent.BusySpinIdleStrategy)1 IdleStrategy (org.agrona.concurrent.IdleStrategy)1 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)1