【问题标题】:How to configure Redis caching in Spring Boot?如何在 Spring Boot 中配置 Redis 缓存?
【发布时间】:2017-12-28 03:43:17
【问题描述】:

如何使用 Spring Boot 配置 Redis 缓存。据我所知,这只是application.properties 文件中的一些更改,但不知道具体是什么。

【问题讨论】:

    标签: java spring caching spring-boot redis


    【解决方案1】:

    要在 Spring Boot 应用程序中使用 Redis 缓存,您只需在 application.properties 文件中设置这些内容

    spring.cache.type=redis
    spring.redis.host=localhost //add host name here
    spring.redis.port=6379
    

    在你的pom.xml中添加这个依赖

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

    此外,您必须在主应用程序类上使用@EnableCaching,并在使用缓存的方法上使用@Cacheable 注释。这就是在 Spring 引导应用程序中使用 redis 所需要的一切。在本例中为 RedisCacheManager,您可以通过自动装配 CacheManager 在任何类中使用它。

    @Autowired
    RedisCacheManager redisCacheManager;
    

    【讨论】:

      【解决方案2】:

      您可以在 application.properties 文件中提及主机名、端口等所有必需的属性,然后从中读取。

      @Configuration
      @PropertySource("application.properties")
      public class SpringSessionRedisConfiguration {
      
      @Value("${redis.hostname}")
      private String redisHostName;
      
      @Value("${redis.port}")
      private int redisPort;
      
      @Bean
      public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
          return new PropertySourcesPlaceholderConfigurer();
      }
      
      @Bean
      JedisConnectionFactory jedisConnectionFactory() {
          JedisConnectionFactory factory = new JedisConnectionFactory();
          factory.setHostName(redisHostName);
          factory.setPort(redisPort);
          factory.setUsePool(true);
          return factory;
      }
      
      @Bean
      RedisTemplate<Object, Object> redisTemplate() {
          RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
          redisTemplate.setConnectionFactory(jedisConnectionFactory());
          return redisTemplate;
      }
      
      @Bean
      RedisCacheManager cacheManager() {
          RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
          return redisCacheManager;
      }
      

      }

      【讨论】:

      • 我认为,这不是 Spring Boot 方式。在 Spring Boot 中,我们不需要创建所有这些缓存管理器和东西(根据我的阅读和听说)
      • 我想这会给你更多的配置灵活性。
      • 没错,但我需要Spring Boot方式
      • 你找到spring boot方式了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2021-07-03
      • 2019-10-13
      • 1970-01-01
      • 2020-02-16
      • 2019-10-18
      相关资源
      最近更新 更多