Refine search
@GET @Path("/products") @Produces({MediaType.APPLICATION_JSON}) public void list( // Suspend the request @Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx) { // Send a list message to the backend vertx.eventBus().<JsonArray>send("backend", new JsonObject().put("op", "list"), msg -> { // When we get the response we resume the Jax-RS async response if (msg.succeeded()) { JsonArray json = msg.result().body(); if (json != null) { asyncResponse.resume(json.encode()); } else { asyncResponse.resume(Response.status(Response.Status.NOT_FOUND).build()); } } else { asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()); } }); } }
@Test public void testSendWithTimeoutNoTimeoutAfterReply() { String str = TestUtils.randomUnicodeString(1000); long timeout = 1000; eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); msg.reply("a reply"); }); AtomicBoolean received = new AtomicBoolean(); eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { assertFalse(received.get()); assertTrue(ar.succeeded()); received.set(true); // Now wait longer than timeout and make sure we don't receive any other reply vertx.setTimer(timeout * 2, tid -> { testComplete(); }); }); await(); }
MessageConsumer<?> reg = vertices[1].eventBus().consumer(ADDRESS1).handler(msg -> { assertEquals(str, msg.body()); if (options == null) { msg.reply(val); } else { msg.reply(val, options); reg.completionHandler(ar -> { assertTrue(ar.succeeded()); vertices[0].eventBus().send(ADDRESS1, str, onSuccess((Message<R> reply) -> { if (consumer == null) { assertTrue(reply.isSend()); assertEquals(received, reply.body()); if (options != null && options.getHeaders() != null) { assertNotNull(reply.headers()); assertEquals(options.getHeaders().size(), reply.headers().size()); for (Map.Entry<String, String> entry: options.getHeaders().entries()) { assertEquals(reply.headers().get(entry.getKey()), entry.getValue()); consumer.accept(reply.body());
@Override public void start(Future<Void> startFuture) throws Exception { vertx.eventBus().<String>consumer("hello", message -> { message.reply("Hello " + message.body() + " from " + ID); }).completionHandler(startFuture); } }
private void registerHandler() { MessageConsumer<JsonObject> messageConsumer = eventBus.consumer(verticleAddress); messageConsumer.handler(message -> { JsonObject jsonMessage = message.body(); System.out.println(jsonMessage.getValue("message_from_sender_verticle")); JsonObject jsonReply = new JsonObject().put("reply", "how interesting!"); message.reply(jsonReply); }); } }
@Test public void testChangesNotVisibleObject3() { Map<String, Object> map = new HashMap<>(); final JsonObject obj = new JsonObject(map); eb.<JsonObject>consumer("foo").handler((Message<JsonObject> msg) -> { vertx.setTimer(1000, id -> { assertFalse(msg.body().containsKey("b")); testComplete(); }); }); eb.send("foo", obj); map.put("b", "uhqdihuqwd"); await(); }
private void testSend(String address, Object body, boolean headers) throws Exception { CountDownLatch latch = new CountDownLatch(1); client.websocket(websocketURI, ws -> { MessageConsumer<Object> consumer = vertx.eventBus().consumer(address); consumer.handler(msg -> { Object receivedBody = msg.body(); assertEquals(body, receivedBody); if (headers) { checkHeaders(msg); } consumer.unregister(v -> latch.countDown()); }); JsonObject msg = new JsonObject().put("type", "send").put("address", address).put("body", body); ws.writeFrame(io.vertx.core.http.WebSocketFrame.textFrame(msg.encode(), true)); }); awaitLatch(latch); }
private void handleRoot(RoutingContext routingContext) { JsonObject result = new JsonObject(); result.put("welcome", "欢迎使用古诗词·一言"); result.put("api-document", "下面为本API可用的所有类型,使用时,在链接最后面加上 .svg / .txt / .json / .png 可以获得不同格式的输出"); result.put("help", "具体安装方法请访问项目首页 " + config().getString("index.url", "http://localhost/")); vertx.eventBus().<JsonArray>send(Key.GET_HELP_FROM_REDIS, null, res -> { if (res.succeeded()) { result.put("list", res.result().body()); returnJsonWithCache(routingContext, result); } else { routingContext.fail(res.cause()); } }); }
private void sendMessage() { JsonObject jsonMessage = new JsonObject().put("message_from_sender_verticle", "hello consumer"); eventBus.send("Consumer", jsonMessage, messageAsyncResult -> { if(messageAsyncResult.succeeded()) { JsonObject jsonReply = (JsonObject) messageAsyncResult.result().body(); System.out.println("received reply: " + jsonReply.getValue("reply")); } }); } }
@Override public void start(Future<Void> startFuture) throws Exception { HttpServerOptions options = new HttpServerOptions().setPort(config().getInteger("port")); vertx.createHttpServer(options).requestHandler(request -> { String name = request.getParam("name"); if (name == null) { request.response().setStatusCode(400).end("Missing name"); } else { vertx.eventBus().<String>send("hello", name, ar -> { if (ar.succeeded()) { request.response().end(ar.result().body()); } else { request.response().setStatusCode(500).end(ar.cause().getMessage()); } }); } }).listen(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); } }
private void testIsolationGroup(String group1, String group2, int count1, int count2, List<String> isolatedClasses, String verticleID) throws Exception { Map<String, Integer> countMap = new ConcurrentHashMap<>(); vertx.eventBus().<JsonObject>consumer("testcounts").handler((Message<JsonObject> msg) -> { countMap.put(msg.body().getString("deploymentID"), msg.body().getInteger("count")); }); CountDownLatch latch = new CountDownLatch(1); boolean expectedSuccess = Thread.currentThread().getContextClassLoader() instanceof URLClassLoader; try { vertx.deployVerticle(verticleID, new DeploymentOptions(). setIsolationGroup(group1).setIsolatedClasses(isolatedClasses), ar -> { assertTrue(ar.succeeded()); deploymentID1.set(ar.result()); assertEquals(0, TestVerticle.instanceCount.get()); vertx.deployVerticle(verticleID, new DeploymentOptions().setIsolationGroup(group2).setIsolatedClasses(isolatedClasses), ar2 -> { assertTrue(ar2.succeeded()); deploymentID2.set(ar2.result()); assertEquals(0, TestVerticle.instanceCount.get());
@Test public void testSendWithTimeoutNoReply() { String str = TestUtils.randomUnicodeString(1000); eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); }); long timeout = 1000; long start = System.currentTimeMillis(); eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { long now = System.currentTimeMillis(); assertFalse(ar.succeeded()); Throwable cause = ar.cause(); assertTrue(cause instanceof ReplyException); ReplyException re = (ReplyException) cause; assertEquals(-1, re.failureCode()); assertEquals(ReplyFailure.TIMEOUT, re.failureType()); assertTrue(now - start >= timeout); testComplete(); }); await(); }
private void getHelpFromRedis(Message message) { redisClient.lrange(Key.REDIS_HELP_LIST, 0, -1, res -> { if (res.succeeded()) { JsonArray array = res.result(); JsonArray newArray = array.stream() .map(text -> { String prefix = config().getString("api.url", "http://localhost/"); return new JsonObject((String) text).stream() .collect(Collectors.toMap(Map.Entry::getKey, v -> prefix + v.getValue().toString().replace(":", "/"))); }) .collect(JsonCollector.toJsonArray()); message.reply(newArray); } else { log.error("Fail to get data from Redis", res.cause()); message.fail(500, res.cause().getMessage()); } }); }
private void listAlbums(Message<JsonObject> msg) { // issue a find command to mongo to fetch all documents from the "albums" collection. mongo.find("albums", new JsonObject(), lookup -> { // error handling if (lookup.failed()) { msg.fail(500, lookup.cause().getMessage()); return; } // now convert the list to a JsonArray because it will be easier to encode the final object as the response. final JsonArray json = new JsonArray(); for (JsonObject o : lookup.result()) { json.add(o); } msg.reply(json); }); }
@Test public void testRegisterRemote1() { startNodes(2); String str = TestUtils.randomUnicodeString(100); vertices[0].eventBus().<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); testComplete(); }).completionHandler(ar -> { assertTrue(ar.succeeded()); vertices[1].eventBus().send(ADDRESS1, str); }); await(); }
/** * @param message example: {format: "png", categories: [shenghuo, buyi]} */ private void getGushiciFromRedis(Message<JsonObject> message) { JsonArray realCategory = new JsonArray() .add("png".equals(message.body().getString("format")) ? "img" : "json") .addAll(message.body().getJsonArray("categories")); checkAndGetKey(realCategory) .compose(key -> Future.<String>future(s -> redisClient.srandmember(key, s))) // 从 set 随机返回一个对象 .setHandler(res -> { if (res.succeeded()) { message.reply(res.result()); } else { if (res.cause() instanceof ReplyException) { ReplyException exception = (ReplyException) res.cause(); message.fail(exception.failureCode(), exception.getMessage()); } message.fail(500, res.cause().getMessage()); } }); }
@Test public void testSendWithTimeoutNoTimeoutReply() { String str = TestUtils.randomUnicodeString(1000); eb.<String>consumer(ADDRESS1).handler((Message<String> msg) -> { assertEquals(str, msg.body()); msg.reply(23); }); long timeout = 1000; eb.send(ADDRESS1, str, new DeliveryOptions().setSendTimeout(timeout), (AsyncResult<Message<Integer>> ar) -> { assertTrue(ar.succeeded()); assertEquals(23, (int) ar.result().body()); testComplete(); }); await(); }
@Override public void start() throws Exception { // A simple backend vertx.eventBus().<JsonObject>consumer("backend", msg -> { JsonObject json = msg.body(); switch (json.getString("op", "")) { case "get": { String productID = json.getString("id"); msg.reply(products.get(productID)); break; } case "add": { String productID = json.getString("id"); JsonObject product = json.getJsonObject("product"); product.put("id", productID); msg.reply(addProduct(product)); break; } case "list": { JsonArray arr = new JsonArray(); products.forEach((k, v) -> arr.add(v)); msg.reply(arr); break; } default: { msg.fail(0, "operation not permitted"); } } }); }