📝

Spring BootでRedis Clusterに接続する

2022/09/25に公開約2,100字

Spring Data Redisを使ってRedis Clusterに接続するメモ

https://spring.io/projects/spring-data-redis/

環境

  • Spring Boot: 2.7.4
  • Kotlin: 1.6.21

Redis Clusterの準備

docker-compose.yml
version: '3.8'

services:
  redis-cluster:
    image: grokzen/redis-cluster:latest
    ports:
      - "7000-7005:7000-7005"
    environment:
      - "INITIAL_PORT=7000"
      - "REDIS_CLUSTER_IP=0.0.0.0"
      - "IP=0.0.0.0"
      - "BIND_ADDRESS=0.0.0.0"
docker compose up -d

動作確認

docker compose exec redis-cluster redis-cli -p 7000 -c
127.0.0.1:7000> set foo bar
-> Redirected to slot [12182] located at 127.0.0.1:7002
OK
127.0.0.1:7002> set hello world
-> Redirected to slot [866] located at 127.0.0.1:7000
OK
127.0.0.1:7000> get foo
-> Redirected to slot [12182] located at 127.0.0.1:7002
"bar"
127.0.0.1:7002> get hello
-> Redirected to slot [866] located at 127.0.0.1:7000
"world"
127.0.0.1:7000>

Spring Bootの準備

build.gradle
dependencies {
+    implementation("org.springframework.boot:spring-boot-starter-data-redis")
    ...
}
application.yml
spring:
  redis:
    cluster:
      nodes:
        - 0.0.0.0:7000
        - 0.0.0.0:7001
        - 0.0.0.0:7002
        - 0.0.0.0:7003
        - 0.0.0.0:7004
        - 0.0.0.0:7005
    connect-timeout: 2s

動かしてみる

@SpringBootTest
class RedisTest {

    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate

    @ParameterizedTest
    @CsvSource(
        *[
            "apple,         1",
            "banana,        2",
            "lemon,         100",
            "lime,          2_000",
            "strawberry,    700_000"
        ]
    )
    fun test(fruit: String, rank: Int) {
        redisTemplate.opsForValue().set(fruit, rank.toString())
        assertThat(redisTemplate.opsForValue().get(fruit)).isEqualTo(rank.toString())
    }
}

テスト実行後にRedisの確認をしてみる

docker compose exec redis-cluster redis-cli -p 7000 -c
127.0.0.1:7000> keys *
1) "lime"
127.0.0.1:7000> get banana
-> Redirected to slot [9380] located at 127.0.0.1:7001
"2"
127.0.0.1:7001> keys *
1) "banana"
2) "apple"
127.0.0.1:7001>

Discussion

ログインするとコメントできます