美文网首页springbootJava基础springboot进阶
SpringBoot缓存注解介绍+实战

SpringBoot缓存注解介绍+实战

作者: HeloWxl | 来源:发表于2020-03-17 13:54 被阅读0次

声明

1、介绍SpringBoot注解

1.1 @Cacheable

  • 运行流程:
    1. 方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;如果没有找到就创建一个cache组件,这里的获取是由CacheManager来完成的.
    2. 在找到的cache组件中,使用一个参数key来获取缓存的内容,默认是按照@Cacheable注解所在的方法的参数。

1.1.1 Cacheable属性

  • cacheNames/value
    指定缓存组件的名字,将方法的返回值存放在哪个缓存中,是数组的方式,可以指定多个缓存.
  • key
    缓存数据时使用的key,可以用这个属性来指定,默认使用方法参数的值.可以使用SqEL表达式来指定,比如#id方法参数id的值,#a0 #p0 #root.args[0]代表第一个参数.
  • keyGenerator
    key的生成器,可以自己指定key的生成器的组件id
//自定义配置类配置keyGenerator
@Configuration
public class MyCacheConfig {
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString() +"]";
            }
        };
    }
}
  • cacheManager
    指定缓存管理器;或者cacheResolver获取指定解析器
    ​- condition
    指定符合条件的情况下才缓存;如condition="#id>0"
  • unless
    否定缓存,当unless指定的条件为true,方法的返回值不会被缓存,可以获取到结果进行判断;如unless="#result==null";
  • sync
    是否使用异步模式
@Cacheable(cacheNames = "user",keyGenerator = "myKeyGenerator")
    public User getUser(Integer id) {
        System.out.println("查询" + id + "号用户");
        User user = userMapper.getUserId(id);
        return user;
    }

1.2 @CachePut

  • 既调用方法,又更新缓存.
  • 运行流程:
    先调用目标方法,将方法结果添加到缓存中,如果已经存在,则更新.
    1、先调用运行方法;
    2、将目标方法的结果缓存起来
    value:缓存名
    key:缓存的key其中#result表示方法返回的结果(确保更新的key和查询一致即可做到同时更新数据库数据和缓存中的数据)
@CachePut(value="user",key = "#result.id")
    public User updateUser(User user){
        System.out.println("updateUser:"+user);
        userMapper.updateUser(user);
        return user;
    }

1.3 @CacheEvict 清除缓存

  • 属性:
    key: 指定要删除的缓存的key
    allEntries: 指定清除这个缓存中的所有数据,默认是false.
    beforeInvocation : 清除缓存的在方法执行之前还是之后. 默认是false,代表在方法执行后清除.(如果方法在执行过程中出现了异常,就不会删除缓存数据)
@CacheEvict(value = "user",key = "#id")
    public void deleteUser(Integer id){
        System.out.println("deleteUser:"+id);
        userMapper.deleteUserById(id);
    }

1.4 @Caching

  • 定义复杂的缓存规则
@Caching(
            cacheable = {
                    @Cacheable()
            },
            put = {
                    @CachePut(),
                    @CachePut()
            },
            evict = {
                    @CacheEvict()
            }
    )
    public 返回值 方法名(参数类型 参数){
        return 返回结果;
    }

1.5 @EnableCaching

  • 开启缓存注解驱动,否则后面使用的缓存都是无效的

1.6 @CacheConfig

  • 这个注解的作用就是全局配置缓存,比如配置缓存的名字(cacheNames),只需要在类上配置一次,下面的方法就默认以全局的配置为主,不需要进行第二次配置,节省了部分代码。

2、缓存实战

  • 简介
    该项目是基于SSM开发的,工具采用的是idea+mysql+postman。

2.1 项目搭建

搭建一个SpringBoot+Mybatis环境,这个就不多说了。


项目结构.png

2.2 pom.xml

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2.3 Dao层

@Mapper
public interface ArtileDao {
   
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Artile queryById(Integer id);

    /**
     * 新增数据
     *
     * @param artile 实例对象
     * @return 影响行数
     */
    int insert(Artile artile);

    /**
     * 修改数据
     *
     * @param artile 实例对象
     * @return 影响行数
     */
    int update(Artile artile);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(Integer id);

}

2.4 ServiceImpl层

  • 这里的话,我就省略了Service。
  • 我们在service层配置了 @CacheConfig,,并且指定了key,这样的话,我们出了第一次之外,我们都会吧结果混存起来,以后的结果,都会吧这个缓存直接返回。当我们进行更新数据的时候,使用@ CacheEvict来清除缓存,防止调用@Cacheable的时候没有更新缓存。
@Service("artileService")
@CacheConfig(cacheNames = "articleCache")
public class ArtileServiceImpl implements ArtileService {
    @Resource
    private ArtileDao artileDao;

    /**
    * @Description: 根据主键查询
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @Cacheable(value = "articleCache")
    @Override
    public Artile queryById(int id) {
        try {
            //模拟耗时操作
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return this.artileDao.queryById(id);
    }

    /**
    * @Description: 新增数据
    * @params: [artile]
    * @return: int
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @CachePut
    @Override
    public int insert(Artile artile) {
        return this.artileDao.insert(artile);
    }

    /**
    * @Description: 修改数据
    * @params: [artile]
    * @return: com.ustcinfo.cache.entity.Artile
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:57 AM
    */ 
    @CacheEvict(key = "#artile.id")
    @Override
    public int update(Artile artile) {
        return  this.artileDao.update(artile);
    }

    /**
    * @Description: 根据主键删除
    * @params: [id]
    * @return: boolean
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:58 AM
    */ 
    @CacheEvict(key = "#id")
    @Override
    public boolean deleteById(Integer id) {
        return this.artileDao.deleteById(id) > 0;
    }
}

2.5 Controller层

@RestController
@RequestMapping("artile")
public class ArtileController {
    /**
     * 服务对象
     */
    @Resource
    private ArtileService artileService;
    
  /**
    * @Description: 根据主键查询
    * @params: [id]
    * @return: java.util.Map<java.lang.String,java.lang.Object>
    * @Author: wangxianlin
    * @Date: 2020/3/17 1:48 PM
    */ 
    @GetMapping("queryById")
    public Map<String,Object> queryById(@RequestParam("id") int id) {
        Map<String,Object> map = new HashMap<>();
        Long start = System.currentTimeMillis();
        map.put("data",this.artileService.queryById(id));
        Long end = System.currentTimeMillis();
        map.put("time",(end-start));
        return map;
    }

    /**
    * @Description: 新增
    * @params: [artile]
    * @return: int
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:55 AM
    */
    @PostMapping("insert")
    public int insert(@RequestBody Artile artile) {
        return this.artileService.insert(artile);
    }

    /**
    * @Description: 修改
    * @params: [artile]
    * @return: com.ustcinfo.cache.entity.Artile
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:55 AM
    */
    @PostMapping("update")
    public int update(@RequestBody Artile artile) {
        return this.artileService.update(artile);
    }

    /**
    * @Description: 根据主键删除
    * @params: [id]
    * @return: boolean
    * @Author: wangxianlin
    * @Date: 2020/3/17 10:56 AM
    */
    @GetMapping("deleteById")
    public boolean deleteById(@RequestParam("id") Integer id) {
        return this.artileService.deleteById(id);
    }
}

2.6 启动类

@MapperScan("com.ustcinfo.cache.dao")
@SpringBootApplication
//开启缓存注解驱动,否则后面使用的缓存都是无效的
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

3、postman测试

3.1 根据主键查询

  • 第一次进行查询:


    image.png
  • 第二次进行查询:


    image.png

3.2 添加

image.png
  • 在查询一次:


    image.png
    image.png

3.3 修改

image.png
  • 在查询一次:


    在查询一次

3.3 删除

image.png
  • 在查询一次:


    image.png
    image.png

相关文章

网友评论

    本文标题:SpringBoot缓存注解介绍+实战

    本文链接:https://www.haomeiwen.com/subject/cyvoehtx.html