Spring Data Redis Reactiveの紹介
データ]
-
リンク:/tag/redis/[Redis]
1前書き
このチュートリアルでは、Spring Dataの
ReactiveRedisTemplateを使用してRedisオペレーションを設定および実装する方法を学習します。
**
Redisでオブジェクトを格納したり取得したりする方法など、
ReactiveRedisTemplate
の基本的な使い方を詳しく説明します。そして
ReactiveRedisConnection
を使ってRedisコマンドを実行する方法を見ていきます。
基本をカバーするために、https://www.baeldung.com/spring-data-redis-tutorial[Spring Data Redisの紹介]をチェックしてください。
2セットアップ
コードで
__ReactiveRedisTemplate
__を使用するには、まずhttps://search.maven.org/classic/#search%7Cga%7C1%7Ca%3A%22spring-boot-starter-data-redis-reactive%22を追加する必要があります。[Spring BootのRedis Reactiveへの依存]モジュール:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
3構成
その後、Redisサーバーとの接続を確立する必要があります。
localhost:6379
のRedisサーバーに接続する場合は、構成用のコードを追加する必要はありません。
しかし、** 私たちのサーバーがリモートであったり別のポートにあった場合は、
__LettuceConnectionFactory
__コンストラクタでホスト名とポートを指定できます。
@Bean
public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}
4リスト操作
Redisリストは、挿入順でソートされた文字列のリストです。リストから要素を追加または削除するには、要素を左または右からプッシュまたはポップします。
4.1. 文字列テンプレート
リストを扱うには、
String
シリアライゼーションコンテキスト
を提供した
ReactiveRedisTemplate
のインスタンスが必要です。
@Bean
public ReactiveRedisTemplate<String, String> reactiveRedisTemplateString
(ReactiveRedisConnectionFactory connectionFactory) {
return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string());
}
そして作成したばかりのStringテンプレートから、
ReactiveListOperations
のインスタンスを取得できます。
@Autowired
private ReactiveRedisTemplate<String, String> redisTemplate;
private ReactiveListOperations<String, String> reactiveListOps;
@Before
public void setup() {
reactiveListOps = redisTemplate.opsForList();
}
4.2. LPUSHとLPOP
ReactiveListOperationsのインスタンスができたので、
demo
list
をリストの識別子として使用して、リストに対してLPUSH操作を実行しましょう。
その後、リスト上でLPOPを実行して、ポップされた要素を確認します。
@Test
public void givenListAndValues__whenLeftPushAndLeftPop__thenLeftPushAndLeftPop() {
Mono<Long> lPush = reactiveListOps.leftPushAll(LIST__NAME, "first", "second")
.log("Pushed");
StepVerifier.create(lPush)
.expectNext(2L)
.verifyComplete();
Mono<String> lPop = reactiveListOps.leftPop(LIST__NAME)
.log("Popped");
StepVerifier.create(lPop)
.expectNext("second")
.verifyComplete();
}
リアクティブコンポーネントをテストするときは、
StepVerifier
を使用してタスクの完了をブロックできます。
5バリューオペレーション
Stringだけでなく、カスタムオブジェクトも使用することをお勧めします。
それでは、POJOに対する操作を示すために、
Employee
オブジェクトに対して同様の操作をいくつか実行しましょう。
public class Employee implements Serializable {
private String id;
private String name;
private String department;
//... getters and setters
//... hashCode and equals
}
5.1. 従業員テンプレート
ReactiveRedisTemplateの2番目のインスタンスを作成する必要があります。キーにはまだ
String
を使用しますが、今回は
Employee
になります。
@Bean
public ReactiveRedisTemplate<String, Employee> reactiveRedisTemplate(
ReactiveRedisConnectionFactory factory) {
StringRedisSerializer keySerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Employee> valueSerializer =
new Jackson2JsonRedisSerializer<>(Employee.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Employee> builder =
RedisSerializationContext.newSerializationContext(keySerializer);
RedisSerializationContext<String, Employee> context =
builder.value(valueSerializer).build();
return new ReactiveRedisTemplate<>(factory, context);
}
カスタムオブジェクトを正しくシリアル化するためには、Springにその方法を指示する必要があります。ここでは、
に
__
Jackson2JsonRedisSerializer
** を設定することで、Jacksonライブラリを使用するようにテンプレートに指示しました。キーは単なるStringなので、そのために
StringRedisSerializer
__を使用できます。
その後、このシリアライゼーションコンテキストと接続ファクトリを使用して、以前と同様にテンプレートを作成します。
次に、
ReactiveListOperations
を使用して
ReactiveValueOperations
のインスタンスを作成します。
@Autowired
private ReactiveRedisTemplate<String, Employee> redisTemplate;
private ReactiveValueOperations<String, Employee> reactiveValueOps;
@Before
public void setup() {
reactiveValueOps = redisTemplate.opsForValue();
}
5.2. 保存および取得操作
__ReactiveValueOperationsのインスタンスができたので、
let’sがそれを使用して
Employee__のインスタンスを格納します。
@Test
public void givenEmployee__whenSet__thenSet() {
Mono<Boolean> result = reactiveValueOps.set("123",
new Employee("123", "Bill", "Accounts"));
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
}
そして、同じオブジェクトをRedisから取り戻すことができます。
@Test
public void givenEmployeeId__whenGet__thenReturnsEmployee() {
Mono<Employee> fetchedEmployee = reactiveValueOps.get("123");
StepVerifier.create(fetchedEmployee)
.expectNext(new Employee("123", "Bill", "Accounts"))
.verifyComplete();
}
5.3. 有効期限付きの操作
私たちはしばしば自然に期限切れになる
キャッシュに値を入れたい
、そして同じ
__set
__operationでこれを行うことができます。
@Test
public void givenEmployee__whenSetWithExpiry__thenSetsWithExpiryTime()
throws InterruptedException {
Mono<Boolean> result = reactiveValueOps.set("129",
new Employee("129", "John", "Programming"),
Duration.ofSeconds(1));
StepVerifier.create(result)
.expectNext(true)
.verifyComplete();
Thread.sleep(2000L);
Mono<Employee> fetchedEmployee = reactiveValueOps.get("129");
StepVerifier.create(fetchedEmployee)
.expectNextCount(0L)
.verifyComplete();
}
このテストはキャッシュキーが期限切れになるのを待つためにいくつかの独自のブロッキングを行います。
6. Redisコマンド
Redisコマンドは基本的にRedisクライアントがサーバー上で呼び出すことができるメソッドです。そしてRedisは、LPUSHやLPOPのように、すでに見たことがある数十のコマンドをサポートしています。
__Operations
__APIは、Redisのコマンドセットをより高度に抽象化したものです。
ただし、** Redisコマンドプリミティブをより直接的に使用したい場合は、Spring Data Redis Reactiveも
__Commands
__APIを提供します。
それでは、
Commands
APIのレンズを通して、StringおよびKeyコマンドを見てみましょう。
6.1. 文字列とキーコマンド
Redisコマンド操作を実行するために、
ReactiveKeyCommands
と
ReactiveStringCommands.
のインスタンスを取得します
両方とも
ReactiveRedisConnectionFactory
インスタンスから取得できます。
@Bean
public ReactiveKeyCommands keyCommands(ReactiveRedisConnectionFactory
reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection().keyCommands();
}
@Bean
public ReactiveStringCommands stringCommands(ReactiveRedisConnectionFactory
reactiveRedisConnectionFactory) {
return reactiveRedisConnectionFactory.getReactiveConnection().stringCommands();
}
6.2. 設定および取得操作
ReactiveStringCommands
を使用すると、1回の呼び出しで複数のキーを保存できます。基本的には
SETコマンドを複数回呼び出します
。
それから、
ReactiveKeyCommands
、
KEYSコマンド
を呼び出して、これらのキーを取得できます。
@Test
public void givenFluxOfKeys__whenPerformOperations__thenPerformOperations() {
Flux<SetCommand> keys = Flux.just("key1", "key2", "key3", "key4");
.map(String::getBytes)
.map(ByteBuffer::wrap)
.map(key -> SetCommand.set(key).value(key));
StepVerifier.create(stringCommands.set(keys))
.expectNextCount(4L)
.verifyComplete();
Mono<Long> keyCount = keyCommands.keys(ByteBuffer.wrap("key** ".getBytes()))
.flatMapMany(Flux::fromIterable)
.count();
StepVerifier.create(keyCount)
.expectNext(4L)
.verifyComplete();
}
先に述べたように、このAPIははるかに低レベルです。たとえば、
高レベルのオブジェクトを扱う代わりに、
ByteBuffer
を使ってバイトストリームを送信します。また、SETやSCANなどのRedisプリミティブも使用します。
最後に、文字列とキーコマンドはhttps://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/connection/package-summary.html[manyコマンドのうち2つですSpring Data Redisが反応的に公開するインタフェース。
7. 結論
このチュートリアルでは、Spring DataのReactive Redisテンプレートを使用するための基本と、それをアプリケーションと統合するためのさまざまな方法について説明しました。
例の完全なソースコードはhttps://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-data-redis[GitHubで入手可能]です。