微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将Redis与Spring数据缓存一起使用时如何启用分布式/集群缓存

如何解决将Redis与Spring数据缓存一起使用时如何启用分布式/集群缓存

在将Redisspring-boot缓存一起使用时,如何启用分布式/集群缓存。

尤其是通过spring-boot-starter-data-redis使用Redis

解决方法

在spring boot应用程序中启用缓存非常简单。您只需要遵循三个步骤即可。

  • 定义缓存配置
  • 将EnableCaching添加到任何配置类
  • 提供CacheManager bean

对于Redis,我们已经可以配置和创建RedisCacheManager。

缓存配置

@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "cache")
public class CacheConfigurationProperties {
 // Redis host name
  private String redisHost;
 // Redis port
  private int redisPort;
  // Default TTL
  private long timeoutSeconds;
  // TTL per cache,add enties for each cache
  private Map<String,Long> cacheTtls;
}

通过属性或yaml文件设置其值

cache.redisHost=localhost
cache.redisPort=6379
cache.timeoutSeconds=1000
cache.cacheTtls.cach1=100
cache.cacheTtls.cach2=200

创建配置后,可以按构建器为RedisCacheManger创建缓存配置。

@Configuration
@EnableCaching
public class CacheConfig {
  private static RedisCacheConfiguration createCacheConfiguration(long timeoutInSeconds) {
    return RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofSeconds(timeoutInSeconds));
  }

  @Bean
  public LettuceConnectionFactory redisConnectionFactory(CacheConfigurationProperties properties) {
    RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
    redisStandaloneConfiguration.setHostName(properties.getRedisHost());
    redisStandaloneConfiguration.setPort(properties.getRedisPort());
    return new LettuceConnectionFactory(redisStandaloneConfiguration);
  }

  @Bean
  public RedisCacheConfiguration cacheConfiguration(CacheConfigurationProperties properties) {
    return createCacheConfiguration(properties.getTimeoutSeconds());
  }

  @Bean
  public CacheManager cacheManager(
      RedisConnectionFactory redisConnectionFactory,CacheConfigurationProperties properties) {
    Map<String,RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    for (Entry<String,Long> cacheNameAndTimeout : properties.getCacheTtls().entrySet()) {
      cacheConfigurations.put(
          cacheNameAndTimeout.getKey(),createCacheConfiguration(cacheNameAndTimeout.getValue()));
    }

    return RedisCacheManager.builder(redisConnectionFactory)
        .cacheDefaults(cacheConfiguration(properties))
        .withInitialCacheConfigurations(cacheConfigurations)
        .build();
  }
}

如果您正在使用Redis集群,则按照该说明更新缓存属性。在这种情况下,如果您要缓存特定的Bean而不是将这些方法设为私有,则某些Bean将成为主要对象。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。