本文源码:GitHub·点这里 || GitEE·点这里

一、Cache缓存简介

从Spring3开始定义Cache和CacheManager接口来统一不同的缓存技术;

Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;

Cache接口下Spring提供了各种缓存的实现;

如RedisCache,EhCacheCache ,ConcurrentMapCache等;

二、核心API

1、Cache缓存接口

定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等

2、CacheManager

缓存管理器,管理各种缓存(cache)组件

3、@Cacheable 主要针对方法配置,能够根据方法的请求参数对其进行缓存

Cacheable 执行流程
1)方法运行之前,按照cacheNames指定的名字先去查询Cache 缓存组件
2)第一次获取缓存如果没有Cache组件会自动创建
3)Cache中查找缓存的内容,使用一个key,默认就是方法的参数
4)key是按照某种策略生成的;默认是使用keyGenerator生成的,这里使用自定义配置
5)没有查到缓存就调用目标方法;
6)将目标方法返回的结果,放进缓存中 Cacheable 注解属性
cacheNames/value:指定方法返回结果使用的缓存组件的名字,可以指定多个缓存
key:缓存数据使用的key
key/keyGenerator:key的生成器,可以自定义
cacheManager:指定缓存管理器
cacheResolver:指定缓存解析器
condition:指定符合条件的数据才缓存
unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存
sync:是否使用异步模式

4、@CacheEvict

清除缓存

CacheEvict:缓存清除
key:指定要清除的数据
allEntries = true:指定清除这个缓存中所有的数据
beforeInvocation = false:方法之前执行清除缓存,出现异常不执行
beforeInvocation = true:代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除

5、@CachePut

保证方法被调用,又希望结果被缓存。

与@Cacheable区别在于是否每次都调用方法,常用于更新,写入

CachePut:执行方法且缓存方法执行的结果
修改了数据库的某个数据,同时更新缓存;
执行流程
1)先调用目标方法
2)然后将目标方法的结果缓存起来

6、@EnableCaching

开启基于注解的缓存

7、keyGenerator

缓存数据时key生成策略

8、@CacheConfig

统一配置本类的缓存注解的属性

三、与SpringBoot2.0整合

1、核心依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、Cache缓存配置

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
public class CacheConfig {
/**
* 自定义 Cache 的 key 生成器
*/
@Bean("oneKeyGenerator")
public KeyGenerator getKeyGenerator (){
return new KeyGenerator() {
@Override
public Object generate(Object obj, Method method, Object... objects) {
return "KeyGenerator:"+method.getName();
}
} ;
}
}

3、启动类注解开启Cache

@EnableCaching            // 开启Cache 缓存注解
@SpringBootApplication
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class,args) ;
}
}

4、Cache注解使用代码

1)封装增删改查接口

import com.boot.cache.entity.User;
public interface UserService {
// 增、改、查、删
User addUser (User user) ;
User updateUser (Integer id) ;
User selectUser (Integer id) ;
void deleteUser (Integer id);
}

2)Cache注解使用案例

import com.boot.cache.entity.User;
import com.boot.cache.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
// 使用自定义的key生成策略
// 缓存结果key:addUser::KeyGenerator:addUser
@CachePut(value = "addUser",keyGenerator="oneKeyGenerator")
@Override
public User addUser(User user) {
return user ;
}
// 缓存结果key:updateUser::2
@CachePut(value = "updateUser",key = "#result.id")
@Override
public User updateUser(Integer id) {
User user = new User() ;
user.setId(id);
user.setName("smile");
return user;
}
// 缓存结果key: selectUser::3
@Cacheable(cacheNames = "selectUser",key = "#id")
@Override
public User selectUser(Integer id) {
User user = new User() ;
user.setId(id);
user.setName("cicadaSmile");
return user;
}
// 删除指定key: selectUser::3
@CacheEvict(value = "selectUser",key = "#id",beforeInvocation = true)
@Override
public void deleteUser(Integer id) { }
}

5、测试代码块

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CacheApplication.class)
public class CacheTest {
@Resource
private UserService userService ;
// 分别测试:增、改、查、删,四个方法
@Test
public void testAdd (){
User user = new User() ;
user.setId(1);
user.setName("cicada");
userService.addUser(user) ;
}
@Test
public void testUpdate (){
userService.updateUser(2) ;
}
@Test
public void testSelect (){
userService.selectUser(3) ;
}
@Test
public void testDelete (){
userService.deleteUser(3) ;
}
}

四、源代码地址

GitHub·地址
https://github.com/cicadasmile/spring-boot-base
GitEE·地址
https://gitee.com/cicadasmile/spring-boot-base

SpringBoot2.0 基础案例(13):基于Cache注解模式,管理Redis缓存的更多相关文章

  1. SpringBoot2.0 基础案例(12):基于转账案例,演示事务管理操作

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.事务管理简介 1.事务基本概念 一组业务操作ABCD,要么全部 ...

  2. SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...

  3. SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口

    一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...

  4. SpringBoot2.0 基础案例(10):整合Mybatis框架,集成分页助手插件

    一.Mybatis框架 1.mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获 ...

  5. SpringBoot2.0 基础案例(07):集成Druid连接池,配置监控界面

    一.Druid连接池 1.druid简介 Druid连接池是阿里巴巴开源的数据库连接池项目.Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能.功能强大,能防SQL注入,内置Login ...

  6. SpringBoot2.0 基础案例(03):配置系统全局异常映射处理

    一.异常分类 这里的异常分类从系统处理异常的角度看,主要分类两类:业务异常和系统异常. 1.业务异常 业务异常主要是一些可预见性异常,处理业务异常,用来提示用户的操作,提高系统的可操作性. 常见的业务 ...

  7. SpringBoot2.0 基础案例(16):配置Actuator组件,实现系统监控

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Actuator简介 1.监控组件作用 在生产环境中,需要实时 ...

  8. SpringBoot2.0 基础案例(15):配置MongoDB数据库,实现增删改查逻辑

    本文源码:GitHub·点这里 || GitEE·点这里 一.NoSQL简介 1.NoSQL 概念 NoSQL( Not Only SQL ),意即"不仅仅是SQL".对不同于传统 ...

  9. SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式

    一.定时任务 1.基本概念 按照指定时间执行的程序. 2.使用场景 数据分析 数据清理 系统服务监控 二.同步和异步 1.基本概念 同步调用 程序按照代码顺序依次执行,每一行程序都必须等待上一行程序执 ...

随机推荐

  1. c#应用程序带参数运行

    有时候我们需要让软件带参数运行,使用参数控制软件的部分行为, C#默认窗口应用是不带参数的,不过在Main函数的参数手动加上就可以得到参数了. 举例如下: /// <summary> // ...

  2. 升级GCC 6.2编译LLVM的问题

    [ 55%] Built target RTInterception.x86_64 [ 55%] Building ASM object projects/compiler-rt/lib/saniti ...

  3. CATTI二级口译训练

    Vice chancellor, faculty members and dear students, It is my great pleasure and privilege to visit C ...

  4. js(11)

    style对象的相关案例 <!DOCTYPE html> <html> <head> <title>MyHtml.html</title> ...

  5. python3 - 写一个生成双色球号码的一个程序,生成的号码写到文件里面

    写一个生成双色球号码的一个程序,生成的号码写到文件里面 # 中奖号码由6个红色球号码和1个蓝色球号码组成 # 篮球范围:01-16 # 红球范围:01-33 def swq(num): random. ...

  6. Unity 官方自带的例子笔记 - Space Shooter

    首先 买过一本叫 Unity3D开发的书,开篇第一个例子就是大家经常碰见的打飞机的例子,写完后我觉得不好玩.后来买了一本 Unity 官方例子说明的书,第一个例子也是打飞机,但是写完后发现蛮酷的,首先 ...

  7. dmidecode 命令

    dmidecode                                                 #  查看全面硬件信息dmidecode | grep "Product ...

  8. 遁入NOIP记

    回归noip啦 给自己定个小目标 500分起步 在这里列一下需要搞的东西OvO 1.算法基础 模拟 贪心 二分 分治 2.搜索 / 记忆化搜索 剪枝 对抗搜索 3.dp 状压 组合数学 树D 单队 D ...

  9. 洛谷 P2285 [HNOI2004]打鼹鼠

    题目描述 鼹鼠是一种很喜欢挖洞的动物,但每过一定的时间,它还是喜欢把头探出到地面上来透透气的.根据这个特点阿牛编写了一个打鼹鼠的游戏:在一个n*n的网格中,在某些时刻鼹鼠会在某一个网格探出头来透透气. ...

  10. 【Lintcode】120.Word Ladder

    题目: Given two words (start and end), and a dictionary, find the length of shortest transformation se ...