一、简介

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

最新文章

  1. Select Top在不同数据库中的使用
  2. (转)由Uploadify插件想到的Flash无法传递Session和Cookie的问题解决
  3. [设计模式] .NET设计模式笔记 - 有多少种设计模式
  4. Java笔记(三十)&hellip;&hellip;正则表达式
  5. Git for Windows
  6. unity3d在Android端读取修改Json数据
  7. USB键盘数据解析
  8. django模板 实现奇偶分行
  9. JS脚本语言(全称java script:网页里使用的脚本语言:非常强大的语言):基础语法
  10. mysql5.6 主从复制
  11. Java中的移动和复制
  12. Ipython的安装/ipython notebook的简单使用
  13. kafka--producer 发布消息
  14. rails 杂记 - render and layout
  15. shell(1)
  16. [原]pomelo基础知识(一)
  17. Codeforces 1076 E - Vasya and a Tree
  18. Confluence 6 如何考虑设置一个空间的主页
  19. Kubernets 第一讲 初探
  20. 01.如何把.py文件打包成为exe,重点讲解pyinstaller的用法

热门文章

  1. 循序渐进VUE+Element 前端应用开发(6)--- 常规Element 界面组件的使用
  2. 我眼中的华为公有云AI平台--ModelArts
  3. JavaScript (五) js的基本语法 - - - 面向对象、工程模式、内置对象、JSON
  4. CPU efficiency测量标准:DMIPS
  5. Java实现 LeetCode 833 字符串中的查找与替换(暴力模拟)
  6. Java实现P2102 -- 正整数序列
  7. Java实现 蓝桥杯VIP 算法提高 3-3求圆面积表面积体积
  8. Java实现 LeetCode 76 最小覆盖子串
  9. CDN百科 | 假如没有CDN,网络世界会变成什么样?
  10. linux init.d启动停止脚本