Java 使用 Redis

用 Jedis / Lettuce 在 Java 里操作 Redis。

Beginner
Key PointsJedis 轻量直连,Lettuce 基于 Netty 支持异步与集群;生产用连接池。

Jedis 示例

Java
JedisPool pool = new JedisPool("127.0.0.1", 6379);
try (Jedis j = pool.getResource()) {
    j.auth("StrongPass!23");
    j.set("user:1:name", "alice");
    j.incr("views");
    System.out.println(j.get("user:1:name"));
}
Output
alice

Lettuce 异步

Java
RedisClient client = RedisClient.create("redis://StrongPass!23@127.0.0.1:6379");
StatefulRedisConnection<String,String> c = client.connect();
RedisAsyncCommands<String,String> cmd = c.async();
cmd.set("k", "v").thenRun(() -> System.out.println("ok"));
Spring projects use Spring Data Redis (Lettuce under the hood); @Cacheable auto-caches method results into Redis with no hand-written code. Pool and password go in spring.redis config.

Friends & Partners