SpringBoot系列:Spring Boot集成Spring Cache,使用RedisCache

前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache、RedisCache、ConcurrentMapCache等。java

这一节咱们来看看Spring Cache使用RedisCache。git

1、RedisCache使用演示

Redis是一个key-value存储系统,在web应用上被普遍应用,这里就不对其过多描述了。github

本章节示例是在Spring Boot集成Spring Cache的源码基础上进行改造。源码地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cacheweb

使用RedisCache做为缓存,咱们先引入相关依赖。redis

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--redis依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

而后SpringBoot配置文件中,对redis进行配置。spring

server:
  port: 10900

spring:
  profiles:
    active: dev
  redis:
    host: localhost #redis服务器地址
    port: 6379 #redis端口
    password: 1234 #redis密码
    timeout: 60000 #链接超时时间
    database: 0 #数据库索引,默认为0

SpringBoot中使用Redis,能够经过Spring Cache的注解,也能够使用RedisTemplate来实现,大部分状况下,由于注解存在必定局限性不够灵活,通常实际开发中都是使用的RedisTemplate。数据库

附上CacheConfig注入RedisTemplate,若是不须要使用RedisTemplate,直接将@EnableCaching注解加在SpringBoot启动类上便可。缓存

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        redisTemplate.setValueSerializer(serializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

这样就能够开始使用RedisCache了,测试代码与Spring Boot集成Spring Cache一致。springboot

CacheApi接口调用类,方便调用进行测试。服务器

@RestController
@RequestMapping("cache")
public class CacheApi {

    @Autowired
    private CacheService cacheService;

    @GetMapping("get")
    public User  get(@RequestParam int id){
        return cacheService.get(id);
    }

    @PostMapping("set")
    public User  set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
        User u = new User(code, name);
        return cacheService.set(id, u);
    }

    @DeleteMapping("del")
    public void  del(@RequestParam int id){
        cacheService.del(id);
    }
    
}

CacheService缓存业务处理类,添加缓存,更新缓存和删除。

@Slf4j
@Service
public class CacheService {

    private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
        {
            for (int i = 1; i < 100 ; i++) {
                User u = new User("code" + i, "name" + i);
                put(i, u);
            }
        }
     };

    // 获取数据
    @Cacheable(value = "cache", key = "'user:' + #id")
    public User get(int id){
        log.info("经过id{}查询获取", id);
        return dataMap.get(id);
    }

    // 更新数据
    @CachePut(value = "cache", key = "'user:' + #id")
    public User set(int id, User u){
        log.info("更新id{}数据", id);
        dataMap.put(id, u);
        return u;
     }

    //删除数据
    @CacheEvict(value = "cache", key = "'user:' + #id")
    public void del(int id){
        log.info("删除id{}数据", id);
        dataMap.remove(id);
    }
    
}

启动服务进行测试,能够看到缓存功能正常,且打开redis进行查看,也能看到对应的缓存数据。

源码地址:https://github.com/imyanger/springboot-project/tree/master/p21-springboot-cache-redis