Search in sources :

Example 31 with Publication

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

the class Pong method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 */
public static void main(final String[] args) {
    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context();
    if (EMBEDDED_MEDIA_DRIVER) {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }
    if (INFO_FLAG) {
        ctx.availableImageHandler(SamplesUtil::printAvailableImage);
        ctx.unavailableImageHandler(SamplesUtil::printUnavailableImage);
    }
    final IdleStrategy idleStrategy = new BusySpinIdleStrategy();
    System.out.println("Subscribing Ping at " + PING_CHANNEL + " on stream id " + PING_STREAM_ID);
    System.out.println("Publishing Pong at " + PONG_CHANNEL + " on stream id " + PONG_STREAM_ID);
    System.out.println("Using exclusive publications " + EXCLUSIVE_PUBLICATIONS);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(PING_CHANNEL, PING_STREAM_ID);
        Publication publication = EXCLUSIVE_PUBLICATIONS ? aeron.addExclusivePublication(PONG_CHANNEL, PONG_STREAM_ID) : aeron.addPublication(PONG_CHANNEL, PONG_STREAM_ID)) {
        final BufferClaim bufferClaim = new BufferClaim();
        final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> pingHandler(bufferClaim, publication, buffer, offset, length, header);
        while (running.get()) {
            idleStrategy.idle(subscription.poll(fragmentHandler, FRAME_COUNT_LIMIT));
        }
        System.out.println("Shutting down...");
    }
    CloseHelper.close(driver);
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) Aeron(io.aeron.Aeron) Subscription(io.aeron.Subscription) io.aeron.logbuffer(io.aeron.logbuffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Publication(io.aeron.Publication) CloseHelper(org.agrona.CloseHelper) SigInt(org.agrona.concurrent.SigInt) DirectBuffer(org.agrona.DirectBuffer) BusySpinIdleStrategy(org.agrona.concurrent.BusySpinIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) BusySpinIdleStrategy(org.agrona.concurrent.BusySpinIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) Publication(io.aeron.Publication) Aeron(io.aeron.Aeron) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) BusySpinIdleStrategy(org.agrona.concurrent.BusySpinIdleStrategy) Subscription(io.aeron.Subscription)

Example 32 with Publication

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

the class SimplePublisher method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if the thread sleep delay is interrupted.
 */
public static void main(final String[] args) throws InterruptedException {
    // 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);
        // Wait for 5 seconds to connect to a subscriber
        final long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
        while (!publication.isConnected()) {
            if ((deadlineNs - System.nanoTime()) < 0) {
                System.out.println("Failed to connect to subscriber");
                return;
            }
            Thread.sleep(1);
        }
        // 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 if (result == Publication.MAX_POSITION_EXCEEDED) {
                System.out.println("Offer failed due to publication reaching max position");
            } 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 33 with Publication

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

the class StreamingPublisher method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if interrupted during linger.
 */
public static void main(final String[] args) throws InterruptedException {
    if (MESSAGE_LENGTH < SIZE_OF_LONG) {
        throw new IllegalArgumentException("Message length must be at least " + SIZE_OF_LONG + " bytes");
    }
    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?");
        final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
        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();
                OFFER_BUFFER.putLong(0, i);
                idleStrategy.reset();
                while (publication.offer(OFFER_BUFFER, 0, length, null) < 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++;
                    idleStrategy.idle();
                }
                reporter.onMessage(length);
            }
            System.out.println("Done streaming. Back pressure ratio " + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (LINGER_TIMEOUT_MS > 0) {
                System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
                Thread.sleep(LINGER_TIMEOUT_MS);
            }
            printingActive = false;
        } while (barrier.await());
    }
    reporter.halt();
    executor.shutdown();
    CloseHelper.close(driver);
}
Also used : IdleStrategy(org.agrona.concurrent.IdleStrategy) Publication(io.aeron.Publication) ContinueBarrier(org.agrona.console.ContinueBarrier) Aeron(io.aeron.Aeron) MediaDriver(io.aeron.driver.MediaDriver) ExecutorService(java.util.concurrent.ExecutorService)

Example 34 with Publication

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

the class ArchiveCreator method createRecording.

private static void createRecording(final Aeron aeron, final AeronArchive aeronArchive, final long startPosition, final long targetPosition) {
    final int initialTermId = 7;
    recordingNumber++;
    final ChannelUriStringBuilder uriBuilder = new ChannelUriStringBuilder().media("udp").endpoint("localhost:" + recordingNumber).termLength(TERM_LENGTH);
    if (startPosition > 0) {
        uriBuilder.initialPosition(startPosition, initialTermId, TERM_LENGTH);
    }
    try (Publication publication = aeronArchive.addRecordedExclusivePublication(uriBuilder.build(), STREAM_ID)) {
        final CountersReader counters = aeron.countersReader();
        final int counterId = awaitRecordingCounterId(counters, publication.sessionId());
        final long recordingId = RecordingPos.getRecordingId(counters, counterId);
        System.out.println("recordingId=" + recordingId + " position " + publication.position() + " to " + targetPosition);
        offerToPosition(publication, targetPosition);
        awaitPosition(counters, counterId, publication.position());
        aeronArchive.stopRecording(publication);
    }
}
Also used : ChannelUriStringBuilder(io.aeron.ChannelUriStringBuilder) Publication(io.aeron.Publication) CountersReader(org.agrona.concurrent.status.CountersReader)

Example 35 with Publication

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

the class EmbeddedThroughput method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if the thread is interrupted during linger.
 */
public static void main(final String[] args) throws InterruptedException {
    loadPropertiesFiles(args);
    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), EmbeddedThroughput::printRate);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final AtomicBoolean running = new AtomicBoolean(true);
    try (MediaDriver mediaDriver = MediaDriver.launch();
        Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()));
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID)) {
        executor.execute(reporter);
        executor.execute(() -> SamplesUtil.subscriberLoop(rateReporterHandler(reporter), FRAGMENT_COUNT_LIMIT, running).accept(subscription));
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
        do {
            System.out.format("%nStreaming %,d messages of payload length %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++) {
                OFFER_BUFFER.putLong(0, i);
                idleStrategy.reset();
                while (publication.offer(OFFER_BUFFER, 0, MESSAGE_LENGTH, null) < 0) {
                    backPressureCount++;
                    idleStrategy.idle();
                }
            }
            System.out.println("Done streaming. backPressureRatio=" + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (LINGER_TIMEOUT_MS > 0) {
                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 : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) IdleStrategy(org.agrona.concurrent.IdleStrategy) ExecutorService(java.util.concurrent.ExecutorService) ConcurrentPublication(io.aeron.ConcurrentPublication) Publication(io.aeron.Publication) ContinueBarrier(org.agrona.console.ContinueBarrier) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron)

Aggregations

Publication (io.aeron.Publication)71 Aeron (io.aeron.Aeron)37 Test (org.junit.jupiter.api.Test)30 CountersReader (org.agrona.concurrent.status.CountersReader)24 InterruptAfter (io.aeron.test.InterruptAfter)22 MediaDriver (io.aeron.driver.MediaDriver)21 Subscription (io.aeron.Subscription)19 File (java.io.File)14 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 ChannelUriStringBuilder (io.aeron.ChannelUriStringBuilder)10 AeronArchive (io.aeron.archive.client.AeronArchive)10 ThreadingMode (io.aeron.driver.ThreadingMode)10 InterruptingTestCallback (io.aeron.test.InterruptingTestCallback)10 Tests (io.aeron.test.Tests)10 ContinueBarrier (org.agrona.console.ContinueBarrier)10 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)10 FragmentAssembler (io.aeron.FragmentAssembler)9 CloseHelper (org.agrona.CloseHelper)9 DirectBuffer (org.agrona.DirectBuffer)9