Search in sources :

Example 16 with EventBus

use of io.vertx.core.eventbus.EventBus in project vert.x by eclipse.

the class MetricsTest method testReplyFailureTimeout1.

@Test
public void testReplyFailureTimeout1() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    EventBus eb = vertx.eventBus();
    FakeEventBusMetrics metrics = FakeMetricsBase.getMetrics(eb);
    eb.consumer(ADDRESS1, msg -> {
    });
    eb.send(ADDRESS1, "bar", new DeliveryOptions().setSendTimeout(10), ar -> {
        assertTrue(ar.failed());
        latch.countDown();
    });
    awaitLatch(latch);
    assertEquals(1, metrics.getReplyFailureAddresses().size());
    assertEquals(Collections.singletonList(ReplyFailure.TIMEOUT), metrics.getReplyFailures());
}
Also used : EventBus(io.vertx.core.eventbus.EventBus) CountDownLatch(java.util.concurrent.CountDownLatch) DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) Test(org.junit.Test)

Example 17 with EventBus

use of io.vertx.core.eventbus.EventBus in project vert.x by eclipse.

the class EventBusTestBase method testSendWhileUnsubscribing.

@Test
public void testSendWhileUnsubscribing() throws Exception {
    startNodes(2);
    AtomicBoolean unregistered = new AtomicBoolean();
    Verticle sender = new AbstractVerticle() {

        @Override
        public void start() throws Exception {
            getVertx().runOnContext(v -> sendMsg());
        }

        private void sendMsg() {
            if (!unregistered.get()) {
                getVertx().eventBus().send("whatever", "marseille");
                burnCpu();
                getVertx().runOnContext(v -> sendMsg());
            } else {
                getVertx().eventBus().send("whatever", "marseille", ar -> {
                    Throwable cause = ar.cause();
                    assertThat(cause, instanceOf(ReplyException.class));
                    ReplyException replyException = (ReplyException) cause;
                    assertEquals(ReplyFailure.NO_HANDLERS, replyException.failureType());
                    testComplete();
                });
            }
        }
    };
    Verticle receiver = new AbstractVerticle() {

        boolean unregisterCalled;

        @Override
        public void start(Future<Void> startFuture) throws Exception {
            EventBus eventBus = getVertx().eventBus();
            MessageConsumer<String> consumer = eventBus.consumer("whatever");
            consumer.handler(m -> {
                if (!unregisterCalled) {
                    consumer.unregister(v -> unregistered.set(true));
                    unregisterCalled = true;
                }
                m.reply("ok");
            }).completionHandler(startFuture);
        }
    };
    CountDownLatch deployLatch = new CountDownLatch(1);
    vertices[0].exceptionHandler(this::fail).deployVerticle(receiver, onSuccess(receiverId -> {
        vertices[1].exceptionHandler(this::fail).deployVerticle(sender, onSuccess(senderId -> {
            deployLatch.countDown();
        }));
    }));
    awaitLatch(deployLatch);
    await();
    CountDownLatch closeLatch = new CountDownLatch(2);
    vertices[0].close(v -> closeLatch.countDown());
    vertices[1].close(v -> closeLatch.countDown());
    awaitLatch(closeLatch);
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Verticle(io.vertx.core.Verticle) Context(io.vertx.core.Context) Future(io.vertx.core.Future) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) EventBus(io.vertx.core.eventbus.EventBus) MessageCodec(io.vertx.core.eventbus.MessageCodec) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) CharsetUtil(io.netty.util.CharsetUtil) ReplyFailure(io.vertx.core.eventbus.ReplyFailure) JsonObject(io.vertx.core.json.JsonObject) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) ReplyException(io.vertx.core.eventbus.ReplyException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Verticle(io.vertx.core.Verticle) AbstractVerticle(io.vertx.core.AbstractVerticle) Future(io.vertx.core.Future) EventBus(io.vertx.core.eventbus.EventBus) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractVerticle(io.vertx.core.AbstractVerticle) ReplyException(io.vertx.core.eventbus.ReplyException) Test(org.junit.Test)

Example 18 with EventBus

use of io.vertx.core.eventbus.EventBus in project vert.x by eclipse.

the class VertxImpl method close.

@Override
public synchronized void close(Handler<AsyncResult<Void>> completionHandler) {
    if (closed || eventBus == null) {
        // Just call the handler directly since pools shutdown
        if (completionHandler != null) {
            completionHandler.handle(Future.succeededFuture());
        }
        return;
    }
    closed = true;
    closeHooks.run(ar -> {
        deploymentManager.undeployAll(ar1 -> {
            if (haManager() != null) {
                haManager().stop();
            }
            addressResolver.close(ar2 -> {
                eventBus.close(ar3 -> {
                    closeClusterManager(ar4 -> {
                        Set<HttpServer> httpServers = new HashSet<>(sharedHttpServers.values());
                        Set<NetServerBase> netServers = new HashSet<>(sharedNetServers.values());
                        sharedHttpServers.clear();
                        sharedNetServers.clear();
                        int serverCount = httpServers.size() + netServers.size();
                        AtomicInteger serverCloseCount = new AtomicInteger();
                        Handler<AsyncResult<Void>> serverCloseHandler = res -> {
                            if (res.failed()) {
                                log.error("Failure in shutting down server", res.cause());
                            }
                            if (serverCloseCount.incrementAndGet() == serverCount) {
                                deleteCacheDirAndShutdown(completionHandler);
                            }
                        };
                        for (HttpServer server : httpServers) {
                            server.close(serverCloseHandler);
                        }
                        for (NetServerBase server : netServers) {
                            server.close(serverCloseHandler);
                        }
                        if (serverCount == 0) {
                            deleteCacheDirAndShutdown(completionHandler);
                        }
                    });
                });
            });
        });
    });
}
Also used : HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) NetServerImpl(io.vertx.core.net.impl.NetServerImpl) HttpClientImpl(io.vertx.core.http.impl.HttpClientImpl) HttpServer(io.vertx.core.http.HttpServer) NetClientImpl(io.vertx.core.net.impl.NetClientImpl) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) EventBus(io.vertx.core.eventbus.EventBus) WindowsFileSystem(io.vertx.core.file.impl.WindowsFileSystem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) Logger(io.vertx.core.logging.Logger) ThreadFactory(java.util.concurrent.ThreadFactory) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Set(java.util.Set) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) EventLoop(io.netty.channel.EventLoop) ResourceLeakDetector(io.netty.util.ResourceLeakDetector) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Executors(java.util.concurrent.Executors) NetClientOptions(io.vertx.core.net.NetClientOptions) DnsClient(io.vertx.core.dns.DnsClient) Objects(java.util.Objects) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) NetServerOptions(io.vertx.core.net.NetServerOptions) PoolMetrics(io.vertx.core.spi.metrics.PoolMetrics) FileSystem(io.vertx.core.file.FileSystem) HttpClient(io.vertx.core.http.HttpClient) DatagramSocketImpl(io.vertx.core.datagram.impl.DatagramSocketImpl) VerticleFactory(io.vertx.core.spi.VerticleFactory) DatagramSocket(io.vertx.core.datagram.DatagramSocket) DnsClientImpl(io.vertx.core.dns.impl.DnsClientImpl) NetServerBase(io.vertx.core.net.impl.NetServerBase) HashMap(java.util.HashMap) LoggerFactory(io.vertx.core.logging.LoggerFactory) SharedData(io.vertx.core.shareddata.SharedData) VertxMetrics(io.vertx.core.spi.metrics.VertxMetrics) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) TimeoutStream(io.vertx.core.TimeoutStream) HashSet(java.util.HashSet) ServiceHelper(io.vertx.core.ServiceHelper) SharedDataImpl(io.vertx.core.shareddata.impl.SharedDataImpl) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) ExecutorService(java.util.concurrent.ExecutorService) EventBusImpl(io.vertx.core.eventbus.impl.EventBusImpl) Closeable(io.vertx.core.Closeable) EventLoopGroup(io.netty.channel.EventLoopGroup) Vertx(io.vertx.core.Vertx) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Verticle(io.vertx.core.Verticle) File(java.io.File) FileSystemImpl(io.vertx.core.file.impl.FileSystemImpl) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ClusteredEventBus(io.vertx.core.eventbus.impl.clustered.ClusteredEventBus) Handler(io.vertx.core.Handler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NetServerBase(io.vertx.core.net.impl.NetServerBase) HttpServer(io.vertx.core.http.HttpServer) AsyncResult(io.vertx.core.AsyncResult) HashSet(java.util.HashSet)

Example 19 with EventBus

use of io.vertx.core.eventbus.EventBus in project vertx-tcp-eventbus-bridge by vert-x3.

the class TcpEventBusBridgeInteropTest method testInteropWithPlainJava.

@Test
public void testInteropWithPlainJava(TestContext context) {
    final Async async = context.async();
    // register a local consumer
    final EventBus eb = vertx.eventBus();
    eb.consumer("io.vertx", msg -> {
        // assert that headers are received
        context.assertEquals("findAll", msg.headers().get("action"));
        // assert body is not null
        context.assertNotNull(msg.body());
        msg.reply(msg.body());
    });
    // run some plain java (blocking)
    vertx.executeBlocking(f -> {
        try {
            JsonObject headers = new JsonObject();
            headers.put("action", "findAll");
            JsonObject body = new JsonObject();
            body.put("model", "news");
            JsonObject protocol = new JsonObject();
            protocol.put("type", "send");
            protocol.put("headers", headers);
            protocol.put("body", body);
            protocol.put("address", "io.vertx");
            protocol.put("replyAddress", "durp");
            Buffer buffer = Buffer.buffer();
            buffer.appendInt(protocol.encode().getBytes().length);
            buffer.appendString(protocol.encode());
            Socket clientSocket = new Socket("localhost", 7000);
            DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
            output.write(buffer.getBytes());
            DataInputStream input = new DataInputStream(clientSocket.getInputStream());
            int bytesLength = input.readInt();
            byte[] bytes = new byte[bytesLength];
            for (int i = 0; i < bytesLength; i++) {
                bytes[i] = input.readByte();
            }
            input.close();
            output.close();
            clientSocket.close();
            JsonObject reply = new JsonObject(new String(bytes));
            // assert that the body is the same we sent
            context.assertEquals(body, reply.getJsonObject("body"));
            f.complete();
        } catch (IOException e) {
            f.fail(e);
        }
    }, res -> {
        context.assertTrue(res.succeeded());
        async.complete();
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Async(io.vertx.ext.unit.Async) DataOutputStream(java.io.DataOutputStream) JsonObject(io.vertx.core.json.JsonObject) EventBus(io.vertx.core.eventbus.EventBus) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) Socket(java.net.Socket) NetSocket(io.vertx.core.net.NetSocket) Test(org.junit.Test)

Example 20 with EventBus

use of io.vertx.core.eventbus.EventBus in project Summer by yale8848.

the class TestService method test.

public SummerResponse test(Vertx vertx, RoutingContext routingContext) {
    EventBus eb = vertx.eventBus();
    EventMessage eventMessage = EventMessage.message(null);
    eventMessage.setKey("68257");
    return SummerResponse.fail().message("bbb");
}
Also used : EventMessage(ren.yale.java.event.EventMessage) EventBus(io.vertx.core.eventbus.EventBus)

Aggregations

EventBus (io.vertx.core.eventbus.EventBus)24 Test (org.junit.Test)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 Context (io.vertx.core.Context)8 Vertx (io.vertx.core.Vertx)8 Buffer (io.vertx.core.buffer.Buffer)8 DeliveryOptions (io.vertx.core.eventbus.DeliveryOptions)8 MessageConsumer (io.vertx.core.eventbus.MessageConsumer)7 JsonObject (io.vertx.core.json.JsonObject)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 DeploymentOptions (io.vertx.core.DeploymentOptions)5 Future (io.vertx.core.Future)5 Verticle (io.vertx.core.Verticle)5 ReplyFailure (io.vertx.core.eventbus.ReplyFailure)5 FileSystem (io.vertx.core.file.FileSystem)5 Consumer (java.util.function.Consumer)5 CharsetUtil (io.netty.util.CharsetUtil)4 VertxOptions (io.vertx.core.VertxOptions)4 DatagramSocket (io.vertx.core.datagram.DatagramSocket)4 io.vertx.core (io.vertx.core)3