Java 使用 Redis

Java有多个Redis客户端,本课学习Jedis和Lettuce的使用。

Redis Java客户端

主流Java Redis客户端:

💡 选择: 简单场景用Jedis,高性能场景用Lettuce,分布式场景用Redisson。

Jedis

添加依赖

Maven:

XML
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.0</version>
</dependency>

Gradle:

GRADLE
implementation 'redis.clients:jedis:5.1.0'

基本连接

JAVA
import redis.clients.jedis.Jedis;

public class RedisDemo {
    public static void main(String[] args) {
        // 连接Redis
        Jedis jedis = new Jedis("localhost", 6379);
        
        // 测试连接
        System.out.println(jedis.ping()); // PONG
        
        // 关闭连接
        jedis.close();
    }
}

带密码连接

JAVA
Jedis jedis = new Jedis("localhost", 6379);
jedis.auth("your_password");

字符串操作

JAVA
import redis.clients.jedis.Jedis;

Jedis jedis = new Jedis("localhost", 6379);

// SET和GET
jedis.set("name", "Alice");
String name = jedis.get("name"); // "Alice"

// SET带过期时间
jedis.setex("session", 3600, "data"); // 1小时后过期

// MSET和MGET
jedis.mset("key1", "value1", "key2", "value2");
List<String> values = jedis.mget("key1", "key2");

// INCR
jedis.set("counter", "0");
Long count = jedis.incr("counter"); // 1

// DEL
jedis.del("name");

哈希操作

JAVA
Jedis jedis = new Jedis("localhost", 6379);

// HSET和HGET
jedis.hset("user:1", "name", "Alice");
jedis.hset("user:1", "age", "25");
String name = jedis.hget("user:1", "name"); // "Alice"

// HMSET和HMGET
Map<String, String> user = new HashMap<>();
user.put("name", "Bob");
user.put("age", "30");
jedis.hset("user:2", user);

List<String> values = jedis.hmget("user:2", "name", "age");

// HGETALL
Map<String, String> allFields = jedis.hgetAll("user:2");

// HDEL
jedis.hdel("user:2", "age");

列表操作

JAVA
Jedis jedis = new Jedis("localhost", 6379);

// LPUSH和RPUSH
jedis.lpush("mylist", "value1", "value2");
jedis.rpush("mylist", "value3");

// LRANGE
List<String> list = jedis.lrange("mylist", 0, -1);

// LPOP和RPOP
String value = jedis.lpop("mylist");
String value2 = jedis.rpop("mylist");

// LLEN
long length = jedis.llen("mylist");

集合操作

JAVA
Jedis jedis = new Jedis("localhost", 6379);

// SADD
jedis.sadd("myset", "a", "b", "c");

// SMEMBERS
Set<String> members = jedis.smembers("myset");

// SISMEMBER
boolean exists = jedis.sismember("myset", "a"); // true

// SREM
jedis.srem("myset", "a");

// SINTER、SUNION、SDIFF
jedis.sadd("set1", "a", "b", "c");
jedis.sadd("set2", "b", "c", "d");
Set<String> inter = jedis.sinter("set1", "set2"); // [b, c]

有序集合操作

JAVA
Jedis jedis = new Jedis("localhost", 6379);

// ZADD
Map<String, Double> scores = new HashMap<>();
scores.put("player1", 100.0);
scores.put("player2", 200.0);
jedis.zadd("leaderboard", scores);

// ZRANGE
Set<String> top = jedis.zrange("leaderboard", 0, 9);

// ZRANGE WITHSCORES
Set<Tuple> topWithScores = jedis.zrangeWithScores("leaderboard", 0, 9);

// ZSCORE
Double score = jedis.zscore("leaderboard", "player1");

// ZINCRBY
jedis.zincrby("leaderboard", 50.0, "player1");

Jedis连接池

JAVA
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
    private static JedisPool pool;
    
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(100);      // 最大连接数
        config.setMaxIdle(50);        // 最大空闲连接
        config.setMinIdle(10);        // 最小空闲连接
        config.setTestOnBorrow(true); // 获取连接时测试
        
        pool = new JedisPool(config, "localhost", 6379);
    }
    
    public static Jedis getJedis() {
        return pool.getResource();
    }
    
    public static void close() {
        pool.close();
    }
}

// 使用连接池
try (Jedis jedis = RedisPool.getJedis()) {
    jedis.set("key", "value");
    String value = jedis.get("key");
}

Jedis管道

JAVA
Jedis jedis = new Jedis("localhost", 6379);

Pipeline pipeline = jedis.pipelined();

pipeline.set("key1", "value1");
pipeline.set("key2", "value2");
pipeline.set("key3", "value3");
pipeline.get("key1");

List<Object> results = pipeline.syncAndReturnAll();

Jedis事务

JAVA
Jedis jedis = new Jedis("localhost", 6379);

Transaction tx = jedis.multi();

tx.set("key1", "value1");
tx.set("key2", "value2");
tx.incr("counter");

List<Object> results = tx.exec();

Lettuce

添加依赖

Maven:

XML
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.3.0</version>
</dependency>

基本连接

JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnection;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class LettuceDemo {
    public static void main(String[] args) {
        // 创建客户端
        RedisClient client = RedisClient.create("redis://localhost:6379");
        
        // 创建连接
        StatefulRedisConnection<String, String> connection = client.connect();
        
        // 获取同步命令
        RedisCommands<String, String> commands = connection.sync();
        
        // 执行命令
        commands.set("key", "value");
        String value = commands.get("key");
        
        // 关闭连接
        connection.close();
        client.shutdown();
    }
}

异步操作

JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;

RedisClient client = RedisClient.create("redis://localhost:6379");
StatefulRedisConnection<String, String> connection = client.connect();

// 获取异步命令
RedisAsyncCommands<String, String> async = connection.async();

// 异步SET
RedisFuture<String> future = async.set("key", "value");

// 等待结果
String result = future.get();

Lettuce连接池

JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;

ClientResources resources = DefaultClientResources.builder()
    .ioThreadPoolSize(4)
    .computationThreadPoolSize(4)
    .build();

RedisClient client = RedisClient.create(resources, "redis://localhost:6379");

Spring集成

Spring Boot集成

添加依赖:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置:

YAML
# application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: your_password
    database: 0
    lettuce:
      pool:
        max-active: 100
        max-idle: 50
        min-idle: 10

使用:

JAVA
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}

RedisTemplate操作

JAVA
@Autowired
private RedisTemplate<String, Object> redisTemplate;

// 字符串操作
redisTemplate.opsForValue().set("key", "value");
Object value = redisTemplate.opsForValue().get("key");

// 哈希操作
redisTemplate.opsForHash().put("user:1", "name", "Alice");
Object name = redisTemplate.opsForHash().get("user:1", "name");

// 列表操作
redisTemplate.opsForList().leftPush("mylist", "value1");
Object value = redisTemplate.opsForList().leftPop("mylist");

// 集合操作
redisTemplate.opsForSet().add("myset", "a", "b", "c");
Set<Object> members = redisTemplate.opsForSet().members("myset");

// 有序集合操作
redisTemplate.opsForZSet().add("leaderboard", "player1", 100);
Set<Object> top = redisTemplate.opsForZSet().range("leaderboard", 0, 9);

实战案例

案例1:分布式锁(Jedis)

JAVA
import redis.clients.jedis.Jedis;
import java.util.UUID;

public class DistributedLock {
    private Jedis jedis;
    private String lockKey;
    private String identifier;
    private int expireTime;
    
    public DistributedLock(Jedis jedis, String lockKey, int expireTime) {
        this.jedis = jedis;
        this.lockKey = lockKey;
        this.expireTime = expireTime;
        this.identifier = UUID.randomUUID().toString();
    }
    
    public boolean acquire() {
        String result = jedis.set(lockKey, identifier, "NX", "EX", expireTime);
        return "OK".equals(result);
    }
    
    public boolean release() {
        String script = 
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "    return redis.call('del', KEYS[1]) " +
            "else " +
            "    return 0 " +
            "end";
        
        Object result = jedis.eval(script, 1, lockKey, identifier);
        return Long.valueOf(1).equals(result);
    }
}

案例2:缓存工具类

JAVA
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RedisCache {
    private JedisPool pool;
    private ObjectMapper mapper = new ObjectMapper();
    
    public RedisCache(JedisPool pool) {
        this.pool = pool;
    }
    
    public void set(String key, Object value, int expireSeconds) {
        try (Jedis jedis = pool.getResource()) {
            String json = mapper.writeValueAsString(value);
            jedis.setex(key, expireSeconds, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public <T> T get(String key, Class<T> clazz) {
        try (Jedis jedis = pool.getResource()) {
            String json = jedis.get(key);
            if (json != null) {
                return mapper.readValue(json, clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

❓ 常见问题

Q Jedis和Lettuce如何选择?
A Jedis简单易用但不线程安全,Lettuce线程安全且支持异步。推荐Lettuce。
Q Jedis为什么需要连接池?
A Jedis不是线程安全的,每个线程需要独立的连接。连接池复用连接提高性能。
Q Spring Boot默认使用哪个客户端?
A Spring Boot 2.x默认使用Lettuce。
Q 如何处理Redis连接异常?
A 使用try-with-resources确保连接关闭,配置重试机制。
Q RedisTemplate和Jedis如何选择?
A Spring项目用RedisTemplate,非Spring项目用Jedis或Lettuce。

📖 小节

📝 作业

  1. 基本操作: 使用Jedis实现字符串、哈希、列表的基本操作
  2. 连接池: 配置Jedis连接池,测试连接复用
  3. Spring集成: 在Spring Boot项目中使用RedisTemplate
  4. 实战: 实现一个简单的分布式锁或缓存工具类

下一课

下一课我们将学习 Node.js 使用 Redis,学习Node.js操作Redis。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏