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)的实现(一),今天我意外发现,注册中心可以无限 ...
随机推荐
- delphi =------报错
关于delphi软件运行出现Invalid floating point operation的错误的解决办法 关于delphi软件运行出现Invalid floating point operatio ...
- 转!!mysql 查询条件不区分大小写问题
做用户登录模块时,输入用户名(大/小写)和密码 ,mysql都能查出来.-- mysql查询不区分大小写. 转自 http://blog.csdn.net/qishuo_java/article/de ...
- 单独使用celery
单独使用celery 参考 http://docs.celeryproject.org/en/latest/getting-started/index.html https://www.jianshu ...
- appium入门基础知识
1.概念区分: 1)IOS-UIAutomation:随着iOS4.0的发布,苹果公司同时发布了一个名为UIAutomation的测试框架,它可以用来在真实设备和iPhone模拟器上执行自动化测试 学 ...
- Keras网络层之卷积层
卷积层 Cov1D层 keras.layers.convolutional.Conv1D(filters, kernel_size, strides=1, padding='valid', dilat ...
- Redis三(List操作)
List操作 redis中的List在在内存中按照一个name对应一个List来存储.如图: lpush(name,values) 1 2 3 4 5 6 7 8 # 在name对应的list中添加元 ...
- CDN 环境下获取用户IP方法
CDN 环境下获取用户IP方法 1 cdn 自定义header头的X-Real-IP,在后端使用$http_x_real_ip获得 proxy_set_header X-Real-IP $remote ...
- Matplot相关(二)——统计图
Matplotlib:其能够支持所有的2D作图和部分3D作图.能通过交互环境做出印刷质量的图像. ————————缩写定义———————— import matplot.pyplot as plt — ...
- 发布mvc3 遇到的HTTP错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容
今天在发布别人提供的MVC3的程序,正常部署后浏览报错,错误内容如图: 根据IIS提供的解决办法,启用目录浏览,刷新页面发现确实不报错了,但页面是以目录显示的,如图 虽然解决了报错问题,但不是正常的效 ...
- Kattis - honey【DP】
Kattis - honey[DP] 题意 有一只蜜蜂,在它的蜂房当中,蜂房是正六边形的,然后它要出去,但是它只能走N步,第N步的时候要回到起点,给出N, 求方案总数 思路 用DP 因为N == 14 ...