spring boot 整合Redis

开题

首先redis是一个数据库,他还是以键值对的方式存储数据的,我们在用redis的时候可以把它当做一个nosql数据库,也可以把它当成一个缓存数据库,当然redis有好多其他用途,这里不做细谈。

在学习springboot运用缓存前,我们先了解一下spring为我们提供的缓存机制,spring定义了CacheManager抽象接口,针对不同的缓存技术需要实现不同的CacheManager,例如:

spring boot 整合Redis_第1张图片
Paste_Image.png

【注意】:不管我们用那个,我们都需要将其注册为Bean,交给spring的容器去管理。

spring 针对缓存还提供了4个注解来声明缓存规则,如下图:

spring boot 整合Redis_第2张图片
注解

【注意】:要想用上面的几个注解起作用,就在配置类中加 @EnableCaching

spring boot 的支持

在前边提到,spring定义了CacheManager抽象接口,针对不同的缓存技术需要实现不同的CacheManager。对于spring boot 而且我们不需要配置,因为它为CacheManager自动配置了多种实现,所以我们拿来用就好了。

spring boot支持以spring.cache为前缀的属性来配置缓存

spring boot 整合Redis_第3张图片
Paste_Image.png

具体示例我放在gitlab上面了,代码有具体的注解,大家可以借鉴:
https://gitlab.com/nishiwode434/spring_boot_redis_test

maven 依赖:


org.springframework.boot
spring-boot-starter-data-redis

这里有几个关键点:

  • spring.cache.type: redis #这里选redis
  • springcache-names: redisCache, redis-cache #此处可以配置多个redis缓存名字(和mysql相比就是一个表名)
  • spring.redis.database: 2 #此处为redis数据库索引,表示第几个数据库,一般设置为0,因为一般我们用一个就够了,除非数据库分库
  • logging.level.java.sql: debug #显示sql语句
  • logging.level.com.wjs: debug #这个包下的所有debug级别的日志都显示
  • logging.level.org.springframework.data.redis: debug
  • 实体类上要实现Serializable
  • 下面这段代码是配置数据序列化到redis的方式,注意:redisTemplate.afterPropertiesSet();
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        //这一步是必要的,表示:通知spring_boot_redis用我自己的序列化方式
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

具体代码demo查看gitlab:https://gitlab.com/nishiwode434/spring_boot_redis_test

你可能感兴趣的:(spring boot 整合Redis)