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%