io.vertx.core.AbstractVerticle Java Examples
The following examples show how to use
io.vertx.core.AbstractVerticle.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Examples.java From vertx-unit with Apache License 2.0 | 6 votes |
@Source(translate = false) public static void asyncAssertSuccess_02(Vertx vertx, TestContext context) { AtomicBoolean started = new AtomicBoolean(); Async async = context.async(); vertx.deployVerticle(new AbstractVerticle() { public void start() throws Exception { started.set(true); } }, ar -> { if (ar.succeeded()) { context.assertTrue(started.get()); async.complete(); } else { context.fail(ar.cause()); } }); // Can be replaced by vertx.deployVerticle("my.verticle", context.asyncAssertSuccess(id -> { context.assertTrue(started.get()); })); }
Example #2
Source File: CleanupTest.java From vertx-kafka-client with Apache License 2.0 | 6 votes |
@Test // Regression test for ISS-73: undeployment of a verticle with unassigned consumer fails public void testUndeployUnassignedConsumer(TestContext ctx) { Properties config = kafkaCluster.useTo().getConsumerProperties("testUndeployUnassignedConsumer_consumer", "testUndeployUnassignedConsumer_consumer", OffsetResetStrategy.EARLIEST); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); Async async = ctx.async(1); vertx.deployVerticle(new AbstractVerticle() { @Override public void start() { KafkaConsumer<String, String> consumer = KafkaConsumer.create(vertx, config); } }, ctx.asyncAssertSuccess(id -> { vertx.undeploy(id, ctx.asyncAssertSuccess(v2 -> async.complete())); })); async.awaitSuccess(10000); waitUntil("Expected " + countThreads("vert.x-kafka-consumer-thread") + " == " + numVertxKafkaConsumerThread, () -> countThreads("vert.x-kafka-consumer-thread") == numKafkaConsumerNetworkThread); }
Example #3
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 6 votes |
/** * Executes the postConstruct using Reflection. This solves the issue that you can extend from a * VxmsEndpoint or use the static invocation of an AbstractVerticle. * * @param router the http router handler * @param startFuture the vert.x start future * @param registrationObject the object to execute postConstruct */ private static void executePostConstruct(AbstractVerticle registrationObject, Router router, final Future<Void> startFuture) { final Stream<ReflectionExecutionWrapper> reflectionExecutionWrapperStream = Stream .of(new ReflectionExecutionWrapper("postConstruct", registrationObject, new Object[]{router, startFuture}, startFuture), new ReflectionExecutionWrapper("postConstruct", registrationObject, new Object[]{startFuture, router}, startFuture), new ReflectionExecutionWrapper("postConstruct", registrationObject, new Object[]{startFuture}, startFuture)); final Optional<ReflectionExecutionWrapper> methodWrapperToInvoke = reflectionExecutionWrapperStream .filter(ReflectionExecutionWrapper::isPresent).findFirst(); methodWrapperToInvoke.ifPresent(ReflectionExecutionWrapper::invoke); if (!methodWrapperToInvoke.isPresent() && !startFuture.isComplete()) { startFuture.complete(); } }
Example #4
Source File: VertxProducer.java From quarkus with Apache License 2.0 | 6 votes |
/** * Undeploy verticles backed by contextual instances of {@link ApplicationScoped} beans before the application context is * destroyed. Otherwise Vertx may attempt to stop the verticles after the CDI container is shut down. * * @param event * @param beanManager */ void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event, BeanManager beanManager, io.vertx.mutiny.core.Vertx mutiny) { // Only beans with the AbstractVerticle in the set of bean types are considered - we need a deployment id Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE); Context applicationContext = beanManager.getContext(ApplicationScoped.class); for (Bean<?> bean : beans) { if (ApplicationScoped.class.equals(bean.getScope())) { // Only beans with @ApplicationScoped are considered Object instance = applicationContext.get(bean); if (instance != null) { // Only existing instances are considered try { AbstractVerticle verticle = (AbstractVerticle) instance; mutiny.undeploy(verticle.deploymentID()).await().indefinitely(); LOGGER.debugf("Undeployed verticle: %s", instance.getClass()); } catch (Exception e) { // In theory, a user can undeploy the verticle manually LOGGER.debugf("Unable to undeploy verticle %s: %s", instance.getClass(), e.toString()); } } } } }
Example #5
Source File: KubeDiscovery.java From vxms with Apache License 2.0 | 6 votes |
/** * Resolves discovery annotation in AbstractVerticles * * @param service the service where to resolve the annotations * @param kubeConfig the kubernetes config */ public static void resolveBeanAnnotations(AbstractVerticle service, Config kubeConfig) { final JsonObject env = service.config(); final List<Field> serviceNameFields = findServiceFields(service); if (!env.getBoolean("kube.offline", false)) { // online final DefaultKubernetesClient client = new DefaultKubernetesClient(kubeConfig); // TODO be aware of OpenShiftClient if (!serviceNameFields.isEmpty()) { findServiceEntryAndSetValue(service, serviceNameFields, env, client); } else { // TODO check and handle Endpoints & Pods } } else { // resolve properties offline if (!serviceNameFields.isEmpty()) { resolveServicesOffline(service, serviceNameFields, env); } else { // TODO check and handle Endpoints & Pods } } }
Example #6
Source File: TestVertxRestTransport.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testInit() { boolean status = false; try { new MockUp<VertxUtils>() { @Mock public Vertx init(VertxOptions vertxOptions) { return null; } @Mock public <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls, DeploymentOptions options) throws InterruptedException { return true; } }; instance.init(); } catch (Exception e) { status = true; } Assert.assertFalse(status); }
Example #7
Source File: MqttProducerBootstrap.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
public static void main(String[] args) { Verticle verticle = new AbstractVerticle() { @Override public void start() { MqttClient client = MqttClient.create(vertx, new MqttClientOptions() //开启遗言 .setWillFlag(true) .setWillTopic("willTopic") .setWillMessage("hello") .setUsername("admin") .setPassword("123456") .setMaxMessageSize(8192)); client.connect(PORT,HOST, asyncResult -> { Runnable publishTask = () -> { Buffer buffer = Buffer.buffer("发布数据" + PUBLISH_COUNT.incrementAndGet()); client.publish("/hello",buffer, MqttQoS.EXACTLY_ONCE, true, true, asyncResult1 -> { if (asyncResult1.succeeded()) { logger.info("publish {}", asyncResult1); } } ); }; Executors.newScheduledThreadPool(1) .scheduleAtFixedRate(publishTask, 0, 15, TimeUnit.MILLISECONDS); }); } }; Vertx.vertx().deployVerticle(verticle); }
Example #8
Source File: VxmsDiscoveryK8SImpl.java From vxms with Apache License 2.0 | 5 votes |
/** * Init discovery with provided Kubernetes Client configuration * @param service the service to initialize * @param kubeConfig the kubernetes client configuration */ public void initDiscovery(AbstractVerticle service, Config kubeConfig) { final JsonObject config = service.config(); if (!service.getClass().isAnnotationPresent(K8SDiscovery.class)) return; final K8SDiscovery annotation = service.getClass().getAnnotation(K8SDiscovery.class); updateKubeConfig(kubeConfig, config, annotation); // 1.) Check from K8SDiscovery Annotation // 1.1) read properties and from Annotation or from configuration // 2.) init KubernetesClient KubeDiscovery.resolveBeanAnnotations(service, kubeConfig); }
Example #9
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 5 votes |
private static void initEventBusExtensions(AbstractVerticle registrationObject, VxmsShared vxmsShared) { // check for Eventbus extension Optional. ofNullable(getEventBusSPI()). ifPresent(eventbusHandlerSPI -> StreamUtils.asStream(eventbusHandlerSPI).forEach(spi -> { spi .initEventHandler(vxmsShared, registrationObject); log("start event-bus extension: " + spi.getClass().getCanonicalName()); })); }
Example #10
Source File: SpringVerticleFactory.java From spring-vertx-ext with Apache License 2.0 | 5 votes |
/** * Initialize a Spring Context for given Verticle instance. A Verticle MUST be annotated with {@link SpringVerticle} * @param verticle The Verticle Instance where to start the Spring Context */ public static void initSpring(AbstractVerticle verticle) { final Class<?> currentVerticleClass = verticle.getClass(); final Vertx vertx = verticle.getVertx(); if(!currentVerticleClass.isAnnotationPresent(SpringVerticle.class)) { throw new InvalidParameterException("no @SpringVerticle annotation found"); } final SpringVerticle annotation = currentVerticleClass.getAnnotation(SpringVerticle.class); final Class<?> springConfigClass = annotation.springConfig(); // Create the parent context final GenericApplicationContext genericApplicationContext = getGenericApplicationContext( vertx.getClass().getClassLoader()); // 1. Create a new context for each verticle and use the specified spring configuration class if possible AnnotationConfigApplicationContext annotationConfigApplicationContext = getAnnotationConfigApplicationContext( springConfigClass, genericApplicationContext); // 2. Register the Vertx instance as a singleton in spring context annotationConfigApplicationContext.getBeanFactory().registerSingleton(vertx.getClass().getSimpleName(), vertx); // 3. Register a bean definition for this verticle annotationConfigApplicationContext.getBeanFactory().registerSingleton(verticle.getClass().getSimpleName(), verticle); // 4. Add a bean factory post processor to avoid configuration issues addPostprocessorAndUpdateContext(currentVerticleClass, annotationConfigApplicationContext); // 5. perform autowiring annotationConfigApplicationContext.getAutowireCapableBeanFactory().autowireBean(verticle); }
Example #11
Source File: SockJSTestBase.java From vertx-web with Apache License 2.0 | 5 votes |
void startServers() throws Exception { CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(() -> new AbstractVerticle() { @Override public void start(Promise<Void> startFuture) throws Exception { Router router = Router.router(vertx); router.route() .handler(SessionHandler.create(LocalSessionStore.create(vertx)) .setNagHttps(false) .setSessionTimeout(60 * 60 * 1000)); if (preSockJSHandlerSetup != null) { preSockJSHandlerSetup.accept(router); } SockJSHandlerOptions options = new SockJSHandlerOptions().setHeartbeatInterval(2000); SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options); sockJSHandler.socketHandler(socketHandler.get()); router.route("/test/*").handler(sockJSHandler); vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost")) .requestHandler(router) .listen(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); } }, new DeploymentOptions().setInstances(numServers), onSuccess(id -> latch.countDown())); awaitLatch(latch); }
Example #12
Source File: CommandRegistryTest.java From vertx-shell with Apache License 2.0 | 5 votes |
@Test public void testUndeployInVerticleContext(TestContext context) { CommandRegistry registry = CommandRegistry.getShared(vertx); Async async = context.async(); AtomicReference<String> ref = new AtomicReference<>(); vertx.deployVerticle(new AbstractVerticle() { @Override public void start(Promise<Void> startPromise) throws Exception { CommandBuilder command = CommandBuilder.command("hello"); command.processHandler(process -> { }); registry.registerCommand(command.build(vertx), ar -> { if (ar.succeeded()) { startPromise.complete(); } else { startPromise.fail(ar.cause()); } }); } }, context.asyncAssertSuccess(id -> { ref.set(id); async.complete(); })); async.awaitSuccess(5000); vertx.undeploy(ref.get(), context.asyncAssertSuccess(v -> { context.assertEquals(Collections.emptyList(), registry.commands()); })); }
Example #13
Source File: ShellTest.java From vertx-shell with Apache License 2.0 | 5 votes |
@Test public void testEchoCharsDuringExecute(TestContext testContext) throws Exception { TestTtyConnection conn = new TestTtyConnection(vertx); ShellImpl shell = createShell(conn); shell.init().readline(); Async async = testContext.async(); vertx.deployVerticle(new AbstractVerticle() { @Override public void start() { commands.add(CommandBuilder.command("foo").processHandler(process -> { testContext.assertEquals(null, conn.checkWritten("% foo\n")); conn.read("\u0007"); testContext.assertNull(conn.checkWritten("^G")); conn.read("A"); testContext.assertNull(conn.checkWritten("A")); conn.read("\r"); testContext.assertNull(conn.checkWritten("\n")); conn.read("\003"); testContext.assertNull(conn.checkWritten("^C")); conn.read("\004"); testContext.assertNull(conn.checkWritten("^D")); async.complete(); })); } }, testContext.asyncAssertSuccess(id -> { conn.read("foo\r"); })); }
Example #14
Source File: CommandRegistryImpl.java From vertx-shell with Apache License 2.0 | 5 votes |
@Override public CommandRegistry registerCommands(List<Command> commands, Handler<AsyncResult<List<Command>>> doneHandler) { if (closed) { throw new IllegalStateException(); } vertx.deployVerticle(new AbstractVerticle() { @Override public void start() throws Exception { Map<String, CommandRegistration> newReg = new HashMap<>(); for (Command command : commands) { String name = command.name(); if (commandMap.containsKey(name)) { throw new Exception("Command " + name + " already registered"); } CommandRegistration registration = new CommandRegistration(command, deploymentID()); newReg.put(name, registration); } commandMap.putAll(newReg); } @Override public void stop() throws Exception { String deploymentId = deploymentID(); commandMap.values().removeIf(reg -> deploymentId.equals(reg.deploymendID)); } }, ar -> { if (ar.succeeded()) { List<Command> regs = commandMap.values(). stream(). filter(reg -> ar.result().equals(reg.deploymendID)). map(reg -> reg.command). collect(Collectors.toList()); doneHandler.handle(Future.succeededFuture(regs)); } else { doneHandler.handle(Future.failedFuture(ar.cause())); } }); return this; }
Example #15
Source File: RestRsHandler.java From vxms with Apache License 2.0 | 5 votes |
@Override public void initRESTHandler( VxmsShared vxmsShared, Router router, AbstractVerticle service, VxmsRoutes... routes) { if(routes==null || routes.length>0) return; RestRsRouteInitializer.initRESTHandler(vxmsShared, router, service); }
Example #16
Source File: RestBaseHandler.java From vxms with Apache License 2.0 | 5 votes |
@Override public void initRESTHandler( VxmsShared vxmsShared, Router router, AbstractVerticle service, VxmsRoutes... routes) { Objects.requireNonNull(routes,"no routes defined"); // check if VxmsRoutes contains REST routes Stream.of(routes) .filter(r -> r instanceof org.jacpfx.vxms.rest.base.VxmsRESTRoutes) .map(VxmsRESTRoutes.class::cast) .forEach( routesToInit -> RestRouteInitializer.initRESTHandler(vxmsShared, router, routesToInit)); }
Example #17
Source File: VxmsDiscoveryK8SImpl.java From vxms with Apache License 2.0 | 5 votes |
@Override public void initDiscovery(AbstractVerticle service) { final JsonObject config = service.config(); final Vertx vertx = service.getVertx(); if (!service.getClass().isAnnotationPresent(K8SDiscovery.class)) return; final K8SDiscovery annotation = service.getClass().getAnnotation(K8SDiscovery.class); final String customClientClassName = ConfigurationUtil.getStringConfiguration( config, CUSTOM_CLIENT_CONFIGURATION, annotation.customClientConfiguration().getCanonicalName()); final CustomClientConfig custConf = getCustomConfiguration(customClientClassName); final Config customConfiguration = custConf.createCustomConfiguration(vertx); if (customConfiguration == null) { final String master_url = ConfigurationUtil.getStringConfiguration(config, MASTER_URL, annotation.master_url()); final String namespace = ConfigurationUtil.getStringConfiguration(config, NAMESPACE, annotation.namespace()); final Config kubeConfig = new ConfigBuilder().withMasterUrl(master_url).withNamespace(namespace).build(); updateKubeConfig(kubeConfig, config, annotation); // 1.) Check from K8SDiscovery Annotation // 1.1) read properties and from Annotation or from configuration // 2.) init KubernetesClient KubeDiscovery.resolveBeanAnnotations(service, kubeConfig); } else { updateKubeConfig(customConfiguration, config, annotation); KubeDiscovery.resolveBeanAnnotations(service, customConfiguration); } }
Example #18
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 5 votes |
private static void initRESTExtensions(Router router, AbstractVerticle registrationObject, VxmsShared vxmsShared, VxmsRoutes... routes) { // check for REST extension Optional. ofNullable(getRESTSPI()). ifPresent(resthandlerSPI -> StreamUtils.asStream(resthandlerSPI).forEach(spi -> { spi.initRESTHandler(vxmsShared, router, registrationObject, routes); log("start REST extension: " + spi.getClass().getCanonicalName()); })); }
Example #19
Source File: MqttConsumerBootstrap.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
public static void main(String[] args) { Verticle verticle = new AbstractVerticle() { @Override public void start() { MqttClient client = MqttClient.create(vertx, new MqttClientOptions() //开启遗言 .setWillFlag(true) .setWillTopic("willTopic") .setWillMessage("hello") .setUsername("admin") .setPassword("123456") .setMaxMessageSize(8192)); client.connect(PORT,HOST,s -> { client.publishHandler(response -> { String message = new String(response.payload().getBytes()); logger.info("接收到消息: {} from topic {}", message, response.topicName()); }); client.subscribe("#", MqttQoS.AT_LEAST_ONCE.value(), resp -> { logger.info("subscribe {}", resp); }); }); } }; Vertx.vertx().deployVerticle(verticle); }
Example #20
Source File: VertxNetClientServerMetricsTest.java From vertx-micrometer-metrics with Apache License 2.0 | 5 votes |
@Before public void setUp(TestContext ctx) { vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions() .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)) .addDisabledMetricsCategory(MetricsDomain.EVENT_BUS) .addLabels(Label.LOCAL, Label.REMOTE) .setRegistryName(registryName) .setEnabled(true))) .exceptionHandler(ctx.exceptionHandler()); // Filter out remote labels BackendRegistries.getNow(registryName).config().meterFilter( MeterFilter.replaceTagValues(Label.REMOTE.toString(), s -> "_", "localhost:9194")); // Setup server Async serverReady = ctx.async(); vertx.deployVerticle(new AbstractVerticle() { @Override public void start(Promise<Void> future) throws Exception { netServer = vertx.createNetServer(); netServer .connectHandler(socket -> socket.handler(buffer -> socket.write(SERVER_RESPONSE))) .listen(9194, "localhost", r -> { if (r.failed()) { ctx.fail(r.cause()); } else { serverReady.complete(); } }); } }); serverReady.awaitSuccess(); }
Example #21
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 5 votes |
/** * starts the HTTP Endpoint * * @param startFuture the vertx start future * @param server the vertx server * @param topRouter the router object */ private static void initHTTPEndpoint(AbstractVerticle registrationObject, Future<Void> startFuture, HttpServer server, Router topRouter) { server.requestHandler(topRouter::accept).listen(status -> { if (status.succeeded()) { executePostConstruct(registrationObject, topRouter, startFuture); startFuture.setHandler(result -> logStartfuture(startFuture)); } else { startFuture.fail(status.cause()); startFuture.setHandler(result -> logStartfuture(startFuture)); } }); }
Example #22
Source File: VertxCoreProcessor.java From quarkus with Apache License 2.0 | 5 votes |
@BuildStep void registerVerticleClasses(CombinedIndexBuildItem indexBuildItem, BuildProducer<ReflectiveClassBuildItem> reflectiveClass) { for (ClassInfo ci : indexBuildItem.getIndex() .getAllKnownSubclasses(DotName.createSimple(AbstractVerticle.class.getName()))) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ci.toString())); } }
Example #23
Source File: NetworkUtilTest.java From AlipayWechatPlatform with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) { Vertx vertx = Vertx.vertx(); NetworkUtils.init(); System.out.println("===================Test start==================="); vertx.deployVerticle(new AbstractVerticle() { @Override public void start() throws Exception { NetworkUtils.asyncPostString("http://breo.turing.asia/gzwx/smartBox/poll", System.out::println); } }); }
Example #24
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 5 votes |
private static void initExtensions(HttpServer server, Router router, AbstractVerticle registrationObject, VxmsShared vxmsShared, VxmsRoutes... routes) { initDiscoveryxtensions(registrationObject); initWebSocketExtensions(server, registrationObject, vxmsShared); initRESTExtensions(router, registrationObject, vxmsShared, routes); initEventBusExtensions(registrationObject, vxmsShared); }
Example #25
Source File: VxmsEndpoint.java From vxms with Apache License 2.0 | 5 votes |
public static void init(final Future<Void> startFuture, AbstractVerticle registrationObject, VxmsRoutes... routes) { // TODO to be used for build in REST and others final Vertx vertx = registrationObject.getVertx(); final JsonObject config = vertx.getOrCreateContext().config(); vertx.eventBus() .consumer(ConfigurationUtil.getServiceName(config, registrationObject.getClass()) + "-info", VxmsEndpoint::info); initEndpoint(startFuture, registrationObject, new VxmsShared(vertx, new LocalData(vertx)), routes); }
Example #26
Source File: GenericHttpServerTest.java From kiqr with Apache License 2.0 | 5 votes |
@Test public void builderWithConfig(){ RestKiqrServerVerticle.Builder builder = RestKiqrServerVerticle.Builder.serverBuilder(new KStreamBuilder(), new Properties()); AbstractVerticle serverVerticle = builder.withOptions(new HttpServerOptions().setPort(4711)).build(); assertThat(serverVerticle, is(instanceOf(RestKiqrServerVerticle.class))); RestKiqrServerVerticle server = (RestKiqrServerVerticle) serverVerticle; assertThat(server.serverOptions.getPort(), is(equalTo(4711))); }
Example #27
Source File: GenericHttpServerTest.java From kiqr with Apache License 2.0 | 5 votes |
@Test public void builderWithPort(){ RestKiqrServerVerticle.Builder builder = RestKiqrServerVerticle.Builder.serverBuilder(new KStreamBuilder(), new Properties()); AbstractVerticle serverVerticle = builder.withPort(4711).build(); assertThat(serverVerticle, is(instanceOf(RestKiqrServerVerticle.class))); RestKiqrServerVerticle server = (RestKiqrServerVerticle) serverVerticle; assertThat(server.serverOptions.getPort(), is(equalTo(4711))); }
Example #28
Source File: HystrixDashboardProxyEurekaTest.java From standalone-hystrix-dashboard with MIT License | 5 votes |
private static AbstractVerticle fakeEurekaVerticle() { return new AbstractVerticle() { @Override public void start(Future<Void> startFuture) throws Exception { final Router router = Router.router(vertx); router.get("/eureka/v2/apps").handler(context -> { final HttpServerResponse response = context.response(); vertx.fileSystem() .readFile("eureka-data.xml", res -> { if (res.succeeded()) { response.putHeader(HttpHeaders.CONTENT_TYPE, "application/xml") .end(res.result()); } else { response.setStatusCode(500) .end("Error while reading eureka data from classpath"); } }); }); vertx.createHttpServer(new HttpServerOptions()) .requestHandler(router::accept) .listen(FAKE_EUREKA_SERVER_PORT, res -> { if (res.succeeded()) { startFuture.complete(); } else { startFuture.fail(res.cause()); } }); } }; }
Example #29
Source File: CleanupTest.java From vertx-kafka-client with Apache License 2.0 | 5 votes |
@Test public void testCleanupInConsumer(TestContext ctx) { String topicName = "testCleanupInConsumer"; Properties config = kafkaCluster.useTo().getConsumerProperties("testCleanupInConsumer_consumer", "testCleanupInConsumer_consumer", OffsetResetStrategy.EARLIEST); config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); Async async = ctx.async(2); Async produceLatch = ctx.async(); vertx.deployVerticle(new AbstractVerticle() { boolean deployed = false; @Override public void start(Promise<Void> fut) { KafkaConsumer<String, String> consumer = KafkaConsumer.create(vertx, config); deployed = true; consumer.handler(record -> { if (deployed) { deployed = false; vertx.undeploy(context.deploymentID(), ctx.asyncAssertSuccess(v2 -> async.countDown())); } }); consumer.assign(new TopicPartition(topicName, 0), fut); } }, ctx.asyncAssertSuccess(v -> produceLatch.complete())); produceLatch.awaitSuccess(10000); kafkaCluster.useTo().produce("testCleanupInConsumer_producer", 100, new StringSerializer(), new StringSerializer(), async::countDown, () -> new ProducerRecord<>(topicName, "the_value")); async.awaitSuccess(10000); waitUntil("Expected " + countThreads("vert.x-kafka-consumer-thread") + " == " + numVertxKafkaConsumerThread, () -> countThreads("vert.x-kafka-consumer-thread") == numKafkaConsumerNetworkThread); }
Example #30
Source File: CleanupTest.java From vertx-kafka-client with Apache License 2.0 | 5 votes |
@Test public void testCleanupInProducer(TestContext ctx) { Properties config = kafkaCluster.useTo().getProducerProperties("the_producer"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); Async deployLatch = ctx.async(); AtomicReference<KafkaProducer<String, String>> producerRef = new AtomicReference<>(); AtomicReference<String> deploymentRef = new AtomicReference<>(); vertx.deployVerticle(new AbstractVerticle() { @Override public void start() throws Exception { KafkaProducer<String, String> producer = KafkaProducer.create(vertx, config); producerRef.set(producer); producer.write(KafkaProducerRecord.create("the_topic", "the_value"), ctx.asyncAssertSuccess()); } }, ctx.asyncAssertSuccess(id -> { deploymentRef.set(id); deployLatch.complete(); })); deployLatch.awaitSuccess(15000); Async undeployLatch = ctx.async(); kafkaCluster.useTo().consumeStrings("the_topic", 1, 10, TimeUnit.SECONDS, () -> { vertx.undeploy(deploymentRef.get(), ctx.asyncAssertSuccess(v -> { undeployLatch.complete(); })); }); undeployLatch.awaitSuccess(10000); waitUntil(() -> countThreads("kafka-producer-network-thread") == numKafkaProducerNetworkThread); }