Springboot- Spring缓存抽象学习笔记
Spring缓存作用准备:
1、准备数据(准备一个有数据的库和表/导入数据库文件,准备好表和表里面的数据)
2、创建javaBean封装数据
3、整合MyBatis操作数据库( 这里用MyBatis)
1,配置数据源信息
2、使用注解版的MyBatis;
1)、@MapperScan指定需要扫描的Mapper接口所在的包
创建一个springboot项目 -》选择依赖(Core->Cache、Web->Web、SQL->MySQL,MyBatis) -》

1,配置数据源信息

spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root spring.datasource.password=root # 不写的时候从url识别 # spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 开启驼峰命名匹配规则,将数据库中表的字段含有下划线分割符的匹配到javaBean的驼峰风格属性
mybatis.configuration.map-underscore-to-camel-case=true
logging.level.com.orz.springbootcache.mapper= debug
2、使用注解版的MyBatis;
1)、@MapperScan指定需要扫描的Mapper接口所在的包
package com.orz.springbootcache.mapper; import com.orz.springbootcache.bean.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; @Mapper
public interface DepartmentMapper { @Select("SELECT * FROM department WHERE id = #{id}")
Department getDeptById(Integer id);
}
package com.orz.springbootcache.mapper; import com.orz.springbootcache.bean.Employee;
import org.apache.ibatis.annotations.*; @Mapper
public interface EmployeeMapper { @Select("SELECT * FROM employee WHERE id = #{id}")
public Employee getEmpById(Integer id); @Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
public void updateEmp(Employee employee); @Delete("DELETE FROM employee WHERE id=#{id}")
public void deleteEmpById(Integer id); @Insert("INSERT INTO employee(lastName,email,gender,d_id) VALUES(#{lastName},#{email},#{gender},#{dId})")
public void insertEmployee(Employee employee); @Select("SELECT * FROM employee WHERE lastName = #{lastName}")
Employee getEmpByLastName(String lastName);
}

EmployeeService
package com.orz.springbootcache.service; import com.orz.springbootcache.bean.Employee;
import com.orz.springbootcache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.ApplicationScope; /**
* @Author ^_^
* @Create 2019/3/10
*/
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
public Employee getEmp(Integer id){
System.out.println("查询"+id + "号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
EmployeeController
package com.orz.springbootcache.controller; import com.orz.springbootcache.bean.Employee;
import com.orz.springbootcache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; /**
* @Author ^_^
* @Create 2019/3/10
*/
@RestController
public class EmployeeController {
@Autowired
EmployeeService employeeService; @GetMapping("/emp/{id}")
public Employee getEmployee(@PathVariable("id") Integer id){
Employee emp = employeeService.getEmp(id);
return emp;
}
}
Spring缓存步骤:
1、开启基于注解的缓存 @EnableCaching
2、标注缓存注解即可
@Cachable
@CachePut
@CacheEvict
@Cachable将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
CacheManager管理多个 Cache组件的,对缓存的真正CRUD操作在 Cache组件中,每一个缓存组件有自己唯一一个名字;
几个属性::
程序入口开启使用缓存@EnableCaching和持久层方法上加入可缓存注解@Cacheable


缓存工作原理和@Cachable工作流程
我们引入了缓存模块,那么缓存的自动配置就会生效
1、自动配置类;CacheAutoConfiguration
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames = {"emp"})
public Employee getEmp(Integer id){
System.out.println("查询"+id + "号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
package com.orz.springbootcache.config; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.lang.reflect.Method;
import java.util.Arrays; /**
* @Author ^_^
* @Create 2019/3/11
*/
@Configuration
public class MyCacheConfig {
@Bean("myKeyGenerator")
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
return method.getName() + "[" + Arrays.asList(objects) + "]";
}
};
}
}
调用自定义KeyGenerator
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator", condition = "#id>0", unless="#a0==2")
public Employee getEmp(Integer id){
System.out.println("查询"+id + "号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
@CachePut
@CachePut: 既调用方法,又更新缓存数据:同步更新缓存
修改了数据库的某个数据,同时更新缓存
运行时机:
1,先调用目标方法
2,将目标方法的结果缓存起来 需要注意缓存的数据
@CachePut 没有指定key时,默认用传参做key,查询result做value
需要要指定和@Cacheable用相同的key,更新的key和查询的key达到一致 service:
package com.orz.springbootcache.service; import com.orz.springbootcache.bean.Employee;
import com.orz.springbootcache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; /**
* @Author ^_^
* @Create 2019/3/10
*/
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames = {"emp"})
public Employee getEmp(Integer id){
System.out.println("查询"+id + "号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
} /**
* @CachePut: 既调用方法,又更新缓存数据:同步更新缓存
* 修改了数据库的某个数据,同时更新缓存
* 运行时机:
* 1,先调用目标方法
* 2,将目标方法的结果缓存起来
*
*
* 需要注意缓存的数据
* @CachePut 没有指定key时,默认用传参做key,查询result做value
* 需要要指定和@Cacheable用相同的key,更新的key和查询的key达到一致
*
*/
@CachePut(value = "emp",key = "#result.id")
public Employee updateEmp(Employee employee){
System.out.println("updateEmp:" + employee);
employeeMapper.updateEmp(employee);
return employee;
}
}
controller
package com.orz.springbootcache.controller; import com.orz.springbootcache.bean.Employee;
import com.orz.springbootcache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; /**
* @Author ^_^
* @Create 2019/3/10
*/
@RestController
public class EmployeeController {
@Autowired
EmployeeService employeeService; @GetMapping("/emp/{id}")
public Employee getEmployee(@PathVariable("id") Integer id){
Employee emp = employeeService.getEmp(id);
return emp;
} @GetMapping("/emp")
public Employee update(Employee employee){
Employee emp = employeeService.updateEmp(employee);
return emp;
}
}
@
Springboot- Spring缓存抽象学习笔记的更多相关文章
- Spring 源码学习笔记11——Spring事务
Spring 源码学习笔记11--Spring事务 Spring事务是基于Spring Aop的扩展 AOP的知识参见<Spring 源码学习笔记10--Spring AOP> 图片参考了 ...
- Spring源码学习笔记12——总结篇,IOC,Bean的生命周期,三大扩展点
Spring源码学习笔记12--总结篇,IOC,Bean的生命周期,三大扩展点 参考了Spring 官网文档 https://docs.spring.io/spring-framework/docs/ ...
- Spring源码学习笔记9——构造器注入及其循环依赖
Spring源码学习笔记9--构造器注入及其循环依赖 一丶前言 前面我们分析了spring基于字段的和基于set方法注入的原理,但是没有分析第二常用的注入方式(构造器注入)(第一常用字段注入),并且在 ...
- java框架之SpringBoot(11)-缓存抽象及整合Redis
Spring缓存抽象 介绍 Spring 从 3.1 版本开始定义了 org.springframework.cache.Cache 和 org.springframework.cache.Cache ...
- 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)
[原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...
- Spring 缓存抽象
Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术:并支 ...
- MVC缓存OutPutCache学习笔记 (二) 缓存及时化VaryByCustom
<MVC缓存OutPutCache学习笔记 (一) 参数配置> 本篇来介绍如何使用 VaryByCustom参数来实现缓存的及时化.. 根据数据改变来及时使客户端缓存过期并更新.. 首先更 ...
- MVC缓存OutPutCache学习笔记 (一) 参数配置
OutPutCache 参数详解 Duration : 缓存时间,以秒为单位,这个除非你的Location=None,可以不添加此属性,其余时候都是必须的. Location : 缓存放置的位置; 该 ...
- spring cloud(学习笔记)高可用注册中心(Eureka)的实现(二)
绪论 前几天我用一种方式实现了spring cloud的高可用,达到两个注册中心,详情见spring cloud(学习笔记)高可用注册中心(Eureka)的实现(一),今天我意外发现,注册中心可以无限 ...
随机推荐
- python中的URL编码和解码
python中的URL编码和解码:test.py # 引入urllib的request模块 import urllib.request url = 'https://www.douban.com/j/ ...
- 巨蟒python全栈开发-第5天 字典&集合
今日大纲: 1.什么是字典 字典是以key:value的形式来保存数据,用{}表示. 存储的是key:value 2.字典的增删改查(重点) (1) 添加 dic[新key] = 值 setdefau ...
- PostgreSQL: WITH Queries (Common Table Expressions)
WITH 允许在 SELECT 语句中定义"表"的表达式,这个"表"的表达式称之为"公共表表达式(Common Table Expression)&q ...
- OVN实战---《The OVN Gateway Router》翻译
Overview 在本文中我将在前文的基础上添加一个OVN gateway router.gateway router将使得lab network能访问我们的overlay network The l ...
- Python元组组成的列表转化为字典
虽然元组.列表不可以直接转化为字典,但下面的确是可行的,因为经常用python从数据库中读出的是元组形式的数据. # 原始数据 rows = (('apollo', 'male', '164.jpeg ...
- SVN入门-2分钟教你入门
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010540106/article/details/37317201 学习SVN首先我们应该知道 ...
- Oracle 11g数据库详解(3)
ORA-14025:不能为实体化视图或实体化视图日志指定PARTITION ORA-14026:PARTITION和CLUSTER子句互相排斥 ORA-14027:仅可以指定一个PARTITION子句 ...
- s5_day14作业
import re # 1. 匹配一段文本中的每行的邮箱 # ret=re.findall('\w+@\w+\.com','10000@qq.com,qwe48645313@163.com') # p ...
- 杭电1021Fibonacci Again
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1021 题目: Problem Description There are another kind of ...
- git使用基础
一.git介绍 git是由 Linus 开发的一种“分布式版本控制”软件,而在此之前,版本控制基本上都是“集中式版本控制”,如:CVS,SVN 等.两者的区别: 1. "集中式版本控制系统& ...