Vert.x 使用Redis

sweetmain發表於2017-12-13
Redis

首先安裝Redis,網上有很多教程,不多說了,說一下Redis的配置檔案,讓其可以在外網訪問 redis.conf

# 設定密碼
requirepass xxxx 
# 把下面這一行註釋掉
bind 127.0.0.1
# 由 yes 改為 no
protected-mode no
複製程式碼

重啟 redis

./redis-server redis.conf
複製程式碼
Vert.x

pom檔案中新增Vert.x Redis依賴

<dependency>
     <groupId>io.vertx</groupId>
    <artifactId>vertx-redis-client</artifactId>
     <version>3.4.1</version>
</dependency>
複製程式碼

Demo.java

public class Demo extends AbstractVerticle {

  private static final Logger logger = LogManager.getLogger(Demo.class);
  private RedisClient redisClient;

  @Override
  public void start() throws Exception {
    RedisOptions config = new RedisOptions().setHost("xxx.xxx.xxx").setPort(6379).setAuth("password");
    redisClient = RedisClient.create(vertx, config);

    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.get("/red").handler(this::queryRedis);

    vertx.createHttpServer().requestHandler(router::accept).listen(8081, r -> {
      if (r.succeeded()) {
        logger.info("服務啟動成功,埠 8081");
      } else {
        logger.error("服務啟動失敗,error :" + r.cause().getMessage());
      }
    });
  }

private void queryRedis(RoutingContext routingContext) {
    redisClient.get("sweet", res -> {
      if (res.succeeded()) {
        routingContext.response().end(Json.encodePrettily(res.result()));
      }else {
        logger.error(res.cause().getMessage());
        res.cause().printStackTrace();
        routingContext.response().setStatusCode(500).end();
      }
    });
  }

public static void main(String[] args) {
    Runner.runExample(Demo.class);
  }
}
複製程式碼

相關文章