1. 程式人生 > 程式設計 >Spring Cache使用RedisCache案例解析

Spring Cache使用RedisCache案例解析

一、RedisCache使用演示

Redis是一個key-value儲存系統,在web應用上被廣泛應用,這裡就不對其過多描述了。

本章節示例是在Spring Boot整合Spring Cache的原始碼基礎上進行改造。原始碼地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

使用RedisCache作為快取,我們先引入相關依賴。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--redis依賴-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

然後SpringBoot配置檔案中,對redis進行配置。

server:
 port: 10900

spring:
 profiles:
  active: dev
 redis:
  host: localhost #redis伺服器地址
  port: 6379 #redis埠
  password: 1234 #redis密碼
  timeout: 60000 #連線超時時間
  database: 0 #資料庫索引,預設為0

SpringBoot中使用Redis,可以通過Spring Cache的註解,也可以使用RedisTemplate來實現,大部分情況下,因為註解存在一定侷限性不夠靈活,一般實際開發中都是使用的RedisTemplate。

附上CacheConfig注入RedisTemplate,如果不需要使用RedisTemplate,直接將@EnableCaching註解加在SpringBoot啟動類上即可。

@Configuration
@EnableCaching
public class CacheConfig {

  @Bean
  public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(connectionFactory);

    // 使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(預設使用JDK的序列化方式)
    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);

    redisTemplate.setValueSerializer(serializer);
    // 使用StringRedisSerializer來序列化和反序列化redis的key值
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }
}

這樣就可以開始使用RedisCache了,測試程式碼與Spring Boot整合Spring Cache一致。

CacheApi介面呼叫類,方便呼叫進行測試。

@RestController
@RequestMapping("cache")
public class CacheApi {

  @Autowired
  private CacheService cacheService;

  @GetMapping("get")
  public User get(@RequestParam int id){
    return cacheService.get(id);
  }

  @PostMapping("set")
  public User set(@RequestParam int id,@RequestParam String code,@RequestParam String name){
    User u = new User(code,name);
    return cacheService.set(id,u);
  }

  @DeleteMapping("del")
  public void del(@RequestParam int id){
    cacheService.del(id);
  }
  
}

CacheService快取業務處理類,新增快取,更新快取和刪除。

@Slf4j
@Service
public class CacheService {

  private Map<Integer,User> dataMap = new HashMap <Integer,User>(){
    {
      for (int i = 1; i < 100 ; i++) {
        User u = new User("code" + i,"name" + i);
        put(i,u);
      }
    }
   };

  // 獲取資料
  @Cacheable(value = "cache",key = "'user:' + #id")
  public User get(int id){
    log.info("通過id{}查詢獲取",id);
    return dataMap.get(id);
  }

  // 更新資料
  @CachePut(value = "cache",key = "'user:' + #id")
  public User set(int id,User u){
    log.info("更新id{}資料",id);
    dataMap.put(id,u);
    return u;
   }

  //刪除資料
  @CacheEvict(value = "cache",key = "'user:' + #id")
  public void del(int id){
    log.info("刪除id{}資料",id);
    dataMap.remove(id);
  }
  
}

啟動服務進行測試,可以看到快取功能正常,且開啟redis進行檢視,也能看到對應的快取資料。

原始碼地址:https://github.com/imyanger/springboot-project/tree/master/p21-springboot-cache-redis

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。