本文主要介绍springboot整合redis缓存,将访问频繁的记录直接缓存,提高页面刷新效率,以及数据库整体性能。

1. pom.xml

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

2. Springboot配置文件

  redis:
    host: 10.245.182.24
    port: 6379
    password: 10086 
    # 连接超时时间 单位 ms(毫秒)
    timeout: 3000
    #=========redis线程池设置=========
    jedis:
      pool:
        # 连接池中的最大空闲连接,默认值是8。
        max-idle: 10 
        # 连接池中的最小大空闲连接,默认值是0。 
        min-idle: 0
        # 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
        max-active: 10
        # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时

3. Redis配置文件

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;

@Configuration
#启动时缓存
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60))
                .disableCachingNullValues();

        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);

        RedisSerializer keySerializer = new StringRedisSerializer(); // 设置key序列化类,否则key前面会多了一些乱码
        template.setKeySerializer(keySerializer);
        setValueSerializer(template);//设置value序列化
        template.afterPropertiesSet();
        template.setEnableTransactionSupport(true);
        return template;
    }

    private void setValueSerializer(StringRedisTemplate template) {
        @SuppressWarnings({"rawtypes", "unchecked"})
        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);
    }
}

4、@Cacheable和@CacheConfig

@Cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。

如果一个方法上添加了@Cacheable标记,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。

缓存是以键值对进行的,值就是方法的返回结果,至于键的话,Spring又支持两种策略,默认策略和自定义策略,需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。

@Cacheable可以指定三个属性,value、key和condition。

 @Cacheable("cache1")//Cache是发生在cache1上的
    public User find(Integer id) {
        return null;
    }

@CacheConfig

这是一个类级别的注解,比如一个类里所有的缓存都是放在cachename为mycache的缓存中,那么每个@Cacheable中都要写value=”mycache”,现在有个更方便的方法了

@CacheConfig(value="books")
public class BookRepositoryImpl implements BookRepository {

    @Cacheable(key="'book'")
    public Book findBook(ISBN isbn) {...}
}

参考文章:

SpringBoot2.0.3 Redis缓存 @Cacheable、@CacheEvict、@CachePut_无人问津的博客-CSDN博客_redis缓存@cacheable

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐