Spring boot 2.X集成Redis做缓存

Redis 简介

什么是 Redis

Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库。

Redis 与其他 key-value 缓存(如 Memcached )相比有以下三个特点:

1.Redis 支持数据的持久化,它可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
2.Redis 不仅仅支持简单的 key-value 类型的数据,同时还提供 list,set,zset,hash 等数据结构的存储。
3.Redis 支持数据的备份,即 master-slave 模式的数据备份。

Redis的优点

  1. 性能极高 – Redis能支持超过 100K+ 每秒的读写频率。
  2. 数据结构丰富 – 除了支持string类型的value外还支持string、hash、set、sortedset、list等数据结构。
  3. 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
  4. 原子性 – Redis的所有操作都是原子性的,同时Redis还支持对几个操作全并后的原子性执行。
  5. 丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。

话不多说,开始上代码

在项目中添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

Redis的配置参数

在application.properties中加入以下配置参数

######redis配置######
#缓存时长,单位:秒
cache.default-exp=30
spring.redis.timeout=3000
spring.redis.database=0
spring.redis.host=localhost
#最大连接数据库连接数,设0为没有限制
spring.redis.jedis.pool.max-active=8
#最大等待连接中的数量,设0为没有限制
spring.redis.jedis.pool.max-idle=8
#最大建立连接等待时间,如果超时将接到异常。设-1表示无限制
spring.redis.jedis.pool.max-wait=1000
#最小等待连接中的数量,设0为没有限制
spring.redis.jedis.pool.min-idle=0

使用注解配置Redis

创建一个名为RedisConfig的class并继承CachingConfigurerSupport,然后在class上添加@Configuration和@EnableCaching注解。

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 RedisConfig2 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);
    }
}

缓存使用示例

分别对@Cacheable和@CacheEvict进行了举例。

//存入缓存
@Cacheable(value = "RedisSave")
    public T findById(ID id) {
        Optional<T> optional = baseDAO.findById(id);
        if(optional.isPresent()) {
            return optional.get();
        }
        return null;
    }
//存入缓存,可使用key自定义存入缓存的key
@Cacheable(value = "RedisSave", key = "'findAll'+#sort.hashCode()")
    public List<T> findAll(Sort sort){
        return baseDAO.findAll(sort);
    }

//清除缓存
    @Transactional
    @CacheEvict(value = "RedisSave", allEntries = true)
    public void save(T entity) {
        baseDAO.save(entity);
    }

最后附上我自己写的一个案例,不是很完善,如果有更好的方法或者其中有什么错误,请一定留言联系我,码云:https://gitee.com/edq/redis.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值