SpringBoot--使用Spring Cache整合redis

一、简介

  Spring Cache是Spring对缓存的封装,适用于 EHCache、Redis、Guava等缓存技术。

二、作用

  主要是可以使用注解的方式来处理缓存,例如,我们使用redis缓存时,查询数据,如果查询到,会判断查到的结果是否为空,如果不为空,则会将结果存入redis缓存,此处需要一层判断;而如果使用Spring Cache的注解进行处理,则不需要判断就可以达到目的。

  示例:

  使用前:

public List<User> selectByUsernameRedis(String username) {
        String key = "user:username:"+username;
        List<User> userList = userMapper.selectByuserName(username);
        if(!userList.isEmpty()){
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(userList));
        }
        return userList;
    }

  使用后:

@Cacheable(value = "user", key = "#username")
    public List<User> selectByUsernameRedis1(String username) {
        return userMapper.selectByuserName(username);
    }

三、配置及使用

  导入包和配置文件与单独集成redis时一致,此处不做描述。

  1、主函数增加@EnableCaching配置,如果主函数不添加@EnableCaching配置,则后面的配置不生效。

  

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

  2、代码实现

  主要有@Cacheable、@CachePut、@CacheEvict三个注解,对应关系如下:

  @Cacheable  查询,先查询缓存,如果存在直接返回;如果不存在,查询数据库,结果不为空,直接存入缓存。

  @CachePut 存入缓存,适用于新增或更新方法。

  @CacheEvict  删除缓存,适用于删除方法。

    @CachePut(value = "user")
    @Override
    public String saveOrUpdate(User user) {
        userMapper.insert(user);
        return JSON.toJSONString(user);
    }

    @Cacheable(value = "user", key = "#id")
    @Override
    public String get(Long id) {
        return JSON.toJSONString(userMapper.selectByUserId(id));
    }

    @CacheEvict(value = "user", key = "#id")
    @Override
    public void delete(Long id) {
        userMapper.deleteByUserId(id);
    }

猜你喜欢

转载自www.cnblogs.com/liconglong/p/11698705.html