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);
}
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.");
}
}
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);
}
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);
}
}
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();
}
}
Aggregations