以下の内容はhttps://uga-box.hatenablog.com/entry/2020/10/09/000000より取得しました。


【Spring Boot】Redisを使う

Cloud Tasksを使っていて、実行されたタスクにエラーが発生した場合は再実行キューにはいる設定にしている

ただ、前回の実行した時のエラーが起こるまでの処理が再実行時には最初から始まってしまっていて、処理が重複してしまっているものがあった

そこで、処理したらRedisに一時的に処理した事実をキャッシュさせておく対策をとることにした

Redis環境

docker-composeでつくる

qiita.com

Springの準備

github.com

pom.xmlに以下を追加

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

application.yamlには以下を追加する

spring.redis:
  host: localhost
  port: 6379
  password: null
  database: 0

これで利用ができる

利用してみる

cacheにキーがあるかどうか

Boolean hasCache = redisTemplate.hasKey(keyName);

https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html#hasKey-K-

単純な文字列をキャッシュさせる

    redisTemplate.opsForValue()
                      .set(keyName, value, 30, TimeUnit.DAYS); // 有効期限30日に設定

opsForValueはRedisのString型を扱うオペレーション

https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisOperations.html#opsForValue--

他参考

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:template




以上の内容はhttps://uga-box.hatenablog.com/entry/2020/10/09/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14