Java 使用 Redis
用 Jedis / Lettuce 在 Java 里操作 Redis。
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
aliceLettuce 异步
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.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
aliceLettuce 异步
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 项目用 Spring Data Redis(底层 Lettuce),
@Cacheable 注解能把方法结果自动塞进 Redis 做缓存,零手工代码。连接池与密码在 spring.redis 配置里设。