spring boot cache 結合 redis 快取機制設定
使用spring boot版本:2.1.6

  1. pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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

 

  1. application.yml
    增加快取管理設定
    reference:
    Redis Sentinel Support https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:sentinel
spring:
  cache:
    type: REDIS
  redis:
    jedis:
      pool:
        max-idle: 8
        min-idle: 0
        max-active: 8
        max-wait: -1
    sentinel:
      master: mymaster
      nodes: 127.0.0.1:26379

 

  1. application.yml
    增加@EnableCaching開啟緩存功能
@SpringBootApplication
@EnableCaching
public class Application {
  
	public static void main(String[] args) {
		SpringApplication.run(Application .class, args);
	}

}

 

基本設定到此,接下來進行程式撰寫

image

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

@Service
public class cacheTestService{

  //delete
    @CacheEvict(value = "idInfo", key = "#id")
    public void delCache(String id) {
      log.error("ENTER DELETE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

  //select (if result is null, don't do insert cache)
    @Cacheable(value = "idInfo", key = "#id", unless = "#result == null")
   public Info getCache(String id) {
    log.error("ENTER GET!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    Info info = infoSrevice.getById(id);
    return info;
  }

  //insert (inset/update cache)
    @CachePut(value = "idInfo", key = "#id")
    public Info insertCache(String id) {
      log.error("ENTER INS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
      Info info = infoSrevice.getById(id);
      return info;
    }
}

 

 

public class Info implements Serializable {
  //存入redis要使用  Serializable 
  // 不然會報錯 "org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type" 
  private Long number;
  private String id;

}

 

相關參考:

[spring] @Cacheable/@CachePut/@CacheEvict protected private or package-visible

    文章標籤

    spring boot redis JAVA 快取

    全站熱搜

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()