spring-boot-2.0.3之redis緩存實現,不是你想的那樣哦

前言
  開心一刻java

    小白問小明:「你前面有一個5米深的坑,裏面沒有水,若是你跳進去後該怎樣出來了?」小明:「躺着出來唄,還能怎麼出來?」小白:「爲何躺着出來?」小明:「5米深的坑,尚未水,跳下去不死就很幸運了,殘是確定會殘的,不躺着出來,那能怎麼出來?」小白:「假設沒死也沒殘呢?」小明:「你當我超人了? 那也簡單,把腦子裏的水放出來就能夠漂出來了。」小白:「你腦子裏有這麼多水嗎?」小明:「我腦子裏沒那麼多水我跳下去幹嗎?」 web

  路漫漫其修遠兮,吾將上下而求索!redis

  springboot 1.x到2.x變更的內容仍是挺多的,而2.x之間也存在細微的差異,本文不講這些差異(具體差異我也不知道,汗......),只講1.5.9與2.0.3的redis緩存配置的區別spring

回到頂部
springboot1.5.9緩存配置
  工程實現
    1.x系列配置應該都差很少,下面咱們看看1.5.9中,springboot集成redis的緩存實現apache

    pom.xmljson

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">;
<modelVersion>4.0.0</modelVersion>緩存

<groupId>com.lee</groupId>
<artifactId>spring-boot159.cache</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <java.version>1.8</java.version>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

<dependencies>

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

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

</dependencies>

</project>
application.ymlspringboot

  server:
port: 8888
spring:
#redis配置
redis:
database: 0
host: 127.0.0.1
port: 6379
password: app

鏈接超時時間(毫秒)

timeout: 2000
pool:less

鏈接池最大鏈接數(使用負值表示沒有限制)

max-active: 8

鏈接池最大阻塞等待時間(使用負值表示沒有限制)

max-wait: -1

鏈接池中的最大空閒鏈接

max-idle: 8

鏈接池中的最小空閒鏈接

min-idle: 0
cache:
type: redis
cache:
expire-time: 180  

    RedisCacheConfig.java

package com.lee.cache.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**

  • 必須繼承CachingConfigurerSupport,否則此類中生成的Bean不會生效(沒有替換掉默認生成的,只是一個普通的bean)
  • springboot默認生成的緩存管理器和redisTemplate支持的類型頗有限,根本不知足咱們的需求,會拋出以下異常:
  • org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.Stringbr/>*/
    @Configuration
    @EnableCaching
    public class RedisCacheConfig extends CachingConfigurerSupport {

    @Value("${cache.expire-time:180}")
    private int expireTime;

    // 配置key生成器,做用於緩存管理器管理的全部緩存
    // 若是緩存註解(@Cacheable、@CacheEvict等)中指定key屬性,那麼會覆蓋此key生成器br/>@Bean
    public KeyGenerator keyGenerator() {
    return (target, method, params) -> {
    StringBuilder sb = new StringBuilder();
    sb.append(target.getClass().getName());
    sb.append(method.getName());
    for (Object obj : params) {
    sb.append(obj.toString());
    }
    return sb.toString();
    };
    }

    // 緩存管理器管理的緩存都須要有對應的緩存空間,不然拋異常:No cache could be resolved for 'Builder...br/>@Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    rcm.setDefaultExpiration(expireTime); //設置緩存管理器管理的緩存的過時時間, 單位:秒
    return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
    }
    }
        CacheServiceImpl.java

package com.lee.cache.service.impl;

import com.lee.cache.model.User;
import com.lee.cache.service.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**

  • 若未配置@CacheConfig(cacheNames = "hello"), 則@Cacheable必定要配置value,至關於指定緩存空間
  • 不然會拋異常:No cache could be resolved for 'Builder...
  • 若@CacheConfig(cacheNames = "hello") 與 @Cacheable(value = "123")都配置了, 則@Cacheable(value = "123")生效
  • 固然@CacheConfig還有一些其餘的配置項,Cacheable也有一些其餘的配置項br/>*/
    @Service
    public class CacheServiceImpl implements ICacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Cacheable(value = "test") // key用的自定義的KeyGenerator
    public String getName() {
    System.out.println("getName, no cache now...");
    return "brucelee";
    }

    @Override
    @Cacheable(value = "user", key = "methodName + '_' + #p0", unless = "#result.size() <= 0") // key會覆蓋掉KeyGenerator
    public List<User> listUser(int pageNum, int pageSize) {
    System.out.println("listUser no cache now...");
    List<User> users = new ArrayList<>();
    users.add(new User("zhengsan", 22));
    users.add(new User("lisi", 20));
    System.out.println("===========");
    return users;
    }

    /**

    • 緩存不是緩存管理器管理,那麼不受緩存管理器的約束
    • 緩存管理器中的配置不適用與此
    • 這裏至關於咱們平時直接經過redis-cli操做redis
    • @returnbr/>*/
      @Override
      public String getUserName() {

      String userName = redisTemplate.opsForValue().get("userName");
      if (!StringUtils.isEmpty(userName)) {
      return userName;
      }

      System.out.println("getUserName, no cache now...");
      redisTemplate.opsForValue().set("userName", "userName");
      return "userName";
      }

}
    上述只講了幾個主要的文件,更多詳情請點springboot159-cache

  redis 怎樣保存cache
    你們必定要把工程仔細看一遍,否則下面出現的一些名稱會讓咱們感受不知從哪來的;

spring-boot-2.0.3之redis緩存實現,不是你想的那樣哦
    工程中的緩存分兩種:緩存管理器管理的緩存(也就是一些列註解實現的緩存)、redisTemplate操做的緩存

      緩存管理器管理的緩存

        會在redis中增長2條數據,一個是類型爲 zset 的 緩存名~keys , 裏面存放了該緩存全部的key, 另外一個是對應的key,值爲序列化後的json;緩存名~keys能夠理解成緩存空間,與咱們平時所說的具體的緩存是不同的。另外對緩存管理器的一些設置(全局過時時間等)都會反映到緩存管理器管理的全部緩存上;上圖中的http://localhost:8888/getName和http://localhost:8888/listUser?pageNum=1&pageSize=3對應的是緩存管理器管理的緩存。

      redisTemplate操做的緩存

        會在redis中增長1條記錄,key - value鍵值對,與咱們經過redis-cli操做緩存同樣;上圖中的http://localhost:8888/getUserName對應的是redisTemplate操做的緩存。

回到頂部
spring2.0.3緩存配置
  工程實現
    pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">;
<modelVersion>4.0.0</modelVersion>

<groupId>com.lee</groupId>
<artifactId>spring-boot-cache</artifactId>
<version>1.0-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
</parent>

<dependencies>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>

</dependencies>

</project>
    application.yml

server:
port: 8889
spring:
#redis配置
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
lettuce:
pool:

接池最大鏈接數(使用負值表示沒有限制)

max-active: 8
    # 鏈接池最大阻塞等待時間(使用負值表示沒有限制)
    max-wait: -1ms
    # 鏈接池中的最小空閒鏈接
    max-idle: 8
    # 鏈接池中的最大空閒鏈接
    min-idle: 0
# 鏈接超時時間
timeout: 2000ms

cache:
type: redis
cache:
test:
expire-time: 180
name: test
default:
expire-time: 200
    緩存定製:RedisCacheManagerConfig.java

package com.lee.cache.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**

  • 進行緩存管理的定製
  • 能夠不配置,採用springboot默認的也行br/>*/
    @Configuration
    public class RedisCacheManagerConfig {

    @Value("${cache.default.expire-time:1800}")
    private int defaultExpireTime;br/>@Value("${cache.test.expire-time:180}")
    private int testExpireTime;br/>@Value("${cache.test.name:test}")
    private String testCacheName;

    //緩存管理器br/>@Bean
    public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) {
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
    // 設置緩存管理器管理的緩存的默認過時時間
    defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(defaultExpireTime))
    // 設置 key爲string序列化
    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
    // 設置value爲json序列化
    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
    // 不緩存空值
    .disableCachingNullValues();

    Set<String> cacheNames = new HashSet<>();
    cacheNames.add(testCacheName);
    
    // 對每一個緩存空間應用不一樣的配置
    Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
    configMap.put(testCacheName, defaultCacheConfig.entryTtl(Duration.ofSeconds(testExpireTime)));
    
    RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
            .cacheDefaults(defaultCacheConfig)
            .initialCacheNames(cacheNames)
            .withInitialCacheConfigurations(configMap)
            .build();
    return cacheManager;

    }
    }
          此類可不用配置,就用spring-boot自動配置的緩存管理器也行,只是在緩存的可閱讀性上會差一些。有興趣的朋友能夠刪除此類試試。

    CacheServiceImpl.java
package com.lee.cache.service.impl;

import com.lee.cache.model.User;
import com.lee.cache.service.ICacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**

  • 若未配置@CacheConfig(cacheNames = "hello"), 則@Cacheable必定要配置value
  • 若@CacheConfig(cacheNames = "hello") 與 @Cacheable(value = "123")都配置了, 則@Cacheable(value = "123") 生效
  • 固然@CacheConfig還有一些其餘的配置項,Cacheable也有一些其餘的配置項br/>*/
    @Service
    public class CacheServiceImpl implements ICacheService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Cacheable(value = "test", key = "targetClass + '_' + methodName")
    public String getName() {
    System.out.println("getName, no cache now...");
    return "brucelee";
    }

    @Override
    @Cacheable(value = "user", key = "targetClass + ':' + methodName + '_' + #p0", unless = "#result.size() <= 0")
    public List<User> listUser(int pageNum, int pageSize) {
    System.out.println("listUser no cache now...");
    List<User> users = new ArrayList<>();
    users.add(new User("zhengsan", 22));
    users.add(new User("lisi", 20));
    return users;
    }

    /**

    • 緩存不是緩存管理器管理,那麼不受緩存管理器的約束
    • 緩存管理器中的配置不適用與此
    • 這裏至關於咱們平時直接經過redis-cli操做redis
    • @returnbr/>*/
      @Override
      public String getUserName() {

      String userName = redisTemplate.opsForValue().get("userName");
      if (StringUtils.isNotEmpty(userName)) {
      return userName;
      }

      System.out.println("getUserName, no cache now...");
      redisTemplate.opsForValue().set("userName", "userName");
      return "userName";
      }

}
    更多詳情請點spring-boot-cache

  redis 怎樣保存cache
    咱們來看圖說話,看看緩存在redis中是如何保存的

spring-boot-2.0.3之redis緩存實現,不是你想的那樣哦
    工程中的緩存分兩種:緩存管理器管理的緩存(也就是一些列註解實現的緩存)、redisTemplate操做的緩存

      緩存管理器管理的緩存

        會在redis中增長1條數據,key是以緩存空間開頭的字符串(緩存空間名::緩存key),值爲序列化後的json;上圖中的http://localhost:8889/getName和http://localhost:8889/listUser?pageNum=1&pageSize=3對應的是緩存管理器管理的緩存。

      redisTemplate操做的緩存

        會在redis中增長1條記錄,key - value鍵值對,與咱們經過redis-cli操做緩存同樣;上圖中的http://localhost:8889/getUserName對應的是redisTemplate操做的緩存。

回到頂部
總結
  一、有時候咱們引入spring-boot-starter-cache這個starter只是爲了快速添加緩存依賴,目的是引入spring-context-support;若是咱們的應用中中已經有了spring-context-support,那麼咱們無需再引入spring-boot-starter-cache,例如咱們的應用中依賴了spring-boot-starter-web,而spring-boot-starter-web中又有spring-context-support依賴,因此咱們無需再引入spring-boot-starter-cache。

  二、Supported Cache Providers,講了支持的緩存類型以及默認狀況下的緩存加載方式,能夠通讀下。

  三、只要咱們引入了redis依賴,並將redis的鏈接信息配置正確,springboot(2.0.3)根據咱們的配置會給咱們生成默認的緩存管理器和redisTemplate;咱們也能夠自定義咱們本身的緩存管理器來替換掉默認的,只要咱們自定義了緩存管理器和redisTemplate,那麼springboot的默認生成的會替換成咱們自定義的。

  四、緩存管理器對緩存的操做也是經過redisTemplate實現的,只是進行了統一的管理,而且可以減小我麼的代碼量,咱們能夠將更多的精力放到業務處理上。

  五、redis-cli -h 127.0.0.1 -p 6379 -a 123456與redis-cli -a 123456兩種方式訪問到的數據徹底不一致,好像操做不一樣的庫同樣! 這個須要注意,有空我回頭看看這二者到底有啥區別,有知道的朋友能夠留個言。

相關文章
相關標籤/搜索