RedisClient状态已断开

时间:2019-01-31 19:30:39

标签: java redis vert.x

我在Windows上将RedisClient与Vert.x一起使用。调试时,RedisClient状态断开,我的API无法正常工作。

这是我的代码:

公共类RedisClientVerticle扩展了AbstractVerticle {

public static final int PORT = 8080;
private RedisClient redis;


@Override
public void start(Future future) throws Exception {
    Router router = Router.router(vertx);

    ServiceDiscovery.create(vertx, serviceDiscovery -> {
        RedisDataSource.getRedisClient(serviceDiscovery, rec -> rec.getName().equals("redis"), ar -> {
            if (ar.failed()) {
                redis = RedisClient.create(vertx, new RedisOptions().setHost("127.0.0.1").setPort(6381));
            } else {
                redis = ar.result();
            }

            router.route("/api/dogs*").handler(BodyHandler.create());
            router.post("/api/dogs").handler(this::addItem);

            vertx.createHttpServer().requestHandler(router::accept).listen(PORT, res -> {
                if (res.succeeded()) {
                    System.out.println("Server listening on port: " + PORT);

                  future.complete();
                } else {
                    System.out.println("Failed to start server.");
                    future.fail(res.cause());
                }
            });
        });
    });
}

private void addItem(RoutingContext context) {
    String body = context.getBodyAsString();
    if (body != null) {
        final Dog dog = Json.decodeValue(body, Dog.class);
        redis.hset("my-dogs-list", dog.getBreed(), Integer.toString(dog.getAge()), res -> {
            if (res.failed()) {
                context.fail(res.cause());
            } else {
                getAll(context);
            }
        });
    } else {
        context.response().setStatusCode(400).end();
    }
}

}

0 个答案:

没有答案