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)的实现(一),今天我意外发现,注册中心可以无限 ...
随机推荐
- 观《phonegap第三季 angularjs+ionic视频教程 实时发布》学习笔记(三)
十五.ionic路由 1.ionic中内联模板介绍 使用内联模板内联模板的使用,常见的有几种情况.(1) 使用ng-include指令可以利用ng-include指令在HTML中直接使用内联模板,例如 ...
- pro-select-limit-if
drop procedure if exists p9; CREATE PROCEDURE p9 () BEGIN DECLARE a INT; DECLARE b INT; DECLARE c IN ...
- sqlalchemy(二)高级用法 2
转自:https://www.cnblogs.com/coder2012/p/4746941.html 外键以及relationship 首先创建数据库,在这里一个user对应多个address,因此 ...
- divison in python2 and python3
python2 >>> / >>> /2.0 1.5 >>> / >>> /2.0 2.0 >>> >& ...
- java 字符串解析为json 使用org.json包的JSONObject+JSONArray
参考: https://blog.csdn.net/xingfei_work/article/details/76572550 java中四种json解析方式 JSONObject+JSONArray ...
- 解决 pip 安装opendr包 卡住的问题
使用豆瓣的源(已经确认过了该源中有opendr包),pip安装opendr,结果卡在了下载完成的位置,什么提示也没有.(如下图) 既然安装包已经下载下来了又安装不上,则应该是安装代码中有什么问题,只不 ...
- Python每日一练------内置函数+内置变量+内置模块
1.内置函数 Python所有的内置函数 Built-in Functions abs() divmod() input() open() staticmethod() all() e ...
- 我的Java开发学习之旅------>Java利用Comparator接口对多个排序条件进行处理
一需求 二实现Comparator接口 三验证排序结果 验证第一条件首先按级别排序级别最高的排在前面 验证第二条如果级别相等那么按工资排序工资高的排在前面 验证第三条如果工资相当则按入职年数排序入职时 ...
- jquery请求数据
$(document).ready(function() { $.ajax({ url: "http://123.207.88.84:8080/zdm/AppApi/Search/Categ ...
- 0407-服务注册与发现-Eureka深入理解-元数据、高可用HA
一.Eureka元数据 参看地址:https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_e ...