SpringBootを使っていてRedisのデータを読み込んだり、Redisにデータを書き込んだりしたいことがある。
今回は、StringRedisTemplateを使ってデータの読み書きする方法を書き溜めする。
StringRedisTemplateはspring-boot-starter-data-redisというライブラリで使用できるクラスです。
pom.xmlに下記を追加してください。
| 1 2 3 4 5 6 | 		<dependency> 			<groupid>org.springframework.boot</groupid> 			<artifactid>spring-boot-starter-data-redis</artifactid> 		</dependency> | 
基本的に「opsForValue」を使って操作します。
application.ymlでRedisの接続情報を指定しておきます。
| 1 2 3 4 5 6 | # resorces/applicaiton.yml spring:   data:     redis:       host: localhost       port: 6379 | 
書き込み
まずopsForValueを書き込む方法は、set()を呼び出すだけです.
| 1 2 3 4 | import org.springframework.data.redis.core.StringRedisTemplate; StringRedisTemplate stringRedisedisTemplate= new StringRedisTemplate(); stringRedisedisTemplate.opsForValue().set("store_key", "store_value"); | 
実際にSpringBoot内で使用するときはDIして使ってください。
| 1 2 3 4 5 | @RequiredArgsConstructor @Service public class RedisService { 	private final StringRedisTemplate stringRedisedisTemplate; } | 
読み込み
Redisから値を参照するには、.get()を使用してください。
| 1 2 3 4 5 | import org.springframework.data.redis.core.StringRedisTemplate; StringRedisTemplate stringRedisedisTemplate= new StringRedisTemplate(); String value = stringRedisedisTemplate.opsForValue().get("store_key"); | 
削除
Redisの値を削除するには、.delete()を使用してください。
| 1 2 3 4 | import org.springframework.data.redis.core.StringRedisTemplate; StringRedisTemplate stringRedisedisTemplate= new StringRedisTemplate(); stringRedisedisTemplate.opsForValue().delete("store_key"); | 
有効期限を設定する
RedisのEXPIREを使うには、getAndExpire()を使ってください。
| 1 2 3 4 | import org.springframework.data.redis.core.StringRedisTemplate; StringRedisTemplate stringRedisedisTemplate= new StringRedisTemplate(); stringRedisedisTemplate.opsForValue().getAndExpire("store_key", 120, TimeUnit.SECONDS); // 120秒 | 
他にも使い方はあるので詳しくはドキュメントみてね。
じゃあねー。
