项目地址:https://gitee.com/indexman/spring_boot_in_action

下面就介绍一下如何使用spring boot自带的缓存。按步骤来操作即可,不懂的可以去看项目源码。

1.新建simple-cache模块,修改pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><artifactId>spring_boot_in_action</artifactId><groupId>com.laoxu</groupId><version>1.0-SNAPSHOT</version></parent><groupId>com.laoxu</groupId><artifactId>simple-cache</artifactId><version>0.0.1-SNAPSHOT</version><name>simple-cache</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2.配置application.yml文件

spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: root123url: jdbc:mysql://localhost:3306/spring_cache?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT&useSSL=falsemybatis:configuration:map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImpldebug: true#redis

3.创建数据库spring_cache,并执行sql

/*
Navicat MySQL Data TransferSource Server         : 本地
Source Server Version : 50528
Source Host           : 127.0.0.1:3306
Source Database       : springboot_cacheTarget Server Type    : MYSQL
Target Server Version : 50528
File Encoding         : 65001Date: 2018-04-27 14:54:04
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`department_name` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (`id` int(11) NOT NULL AUTO_INCREMENT,`last_name` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`gender` int(2) DEFAULT NULL,`d_id` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4.创建实体

package com.laoxu.springboot.bean;public class Department {private Integer id;private String departmentName;public Department() {super();// TODO Auto-generated constructor stub}public Department(Integer id, String departmentName) {super();this.id = id;this.departmentName = departmentName;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}@Overridepublic String toString() {return "Department [id=" + id + ", departmentName=" + departmentName + "]";}}
package com.laoxu.springboot.bean;public class Employee {private Integer id;private String lastName;private String email;private Integer gender; //性别 1男  0女private Integer dId;public Employee() {super();}public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {super();this.id = id;this.lastName = lastName;this.email = email;this.gender = gender;this.dId = dId;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public Integer getdId() {return dId;}public void setdId(Integer dId) {this.dId = dId;}@Overridepublic String toString() {return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="+ dId + "]";}}

5.创建mapper

package com.laoxu.springboot.mapper;import com.laoxu.springboot.bean.Employee;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;@Repository
@Mapper
public interface EmployeeMapper {@Select("SELECT * FROM employee WHERE id=#{id}")Employee getEmpById(Integer id);@Update("update employee set last_name=#{lastName}, email=#{email},gender=#{gender},d_id=#{dId} where id=#{id}")void updateEmp(Employee employee);@Delete("delete from employee where id=#{id}")void deleteEmpById(Integer id);@Insert("insert into employee(last_name,email,gender,d_id)  values(#{lastName}, #{email}, #{gender}, #{dId})")void insertEmp(Employee employee);@Select("SELECT * FROM employee WHERE last_name=#{lastName}")Employee getEmpByLastName(String lastName);}

6.创建service

package com.laoxu.springboot.service;import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@CacheConfig(cacheNames = "emp") //在此处加上就不用在每个方法上加了
@Service
public class EmployeeService {@AutowiredEmployeeMapper employeeMapper;@Cacheable(/*cacheNames = "emp"*//*,keyGenerator = "myKeyGenerator",key = "#id", condition = "#a0>1" , unless = "#a0==1"*/)public Employee getEmp(Integer id){System.out.println("查询"+id+"号员工");return employeeMapper.getEmpById(id);}/*** 在方法后調用, 同步更新缓存* @param employee* @return*/@CachePut(/*cacheNames = "emp",*/ key="#result.id")public Employee updateEmp(Employee employee){System.out.println("更新员工:"+employee);employeeMapper.updateEmp(employee);return employee;}/*** allEntries = true  删除所有emp缓存* beforeInvocation = true 无论方法是否成功 都会删掉缓存* @param id*/@CacheEvict(/*value = "emp",*/ key = "#id")public void deleteEmp(Integer id){System.out.println("删除员工:"+id);}@Caching(cacheable = {@Cacheable(/*value = "emp",*/ key = "#lastName")},put = {@CachePut(/*value = "emp",*/ key = "#result.id"),@CachePut(/*value = "email",*/ key = "#result.email")})public Employee getEmpByLastName(String lastName){return employeeMapper.getEmpByLastName(lastName);}
}

7.创建controller

package com.laoxu.springboot.controller;import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.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;@RestController
public class EmployeeController {@AutowiredEmployeeService employeeService;@GetMapping("/emp/{id}")public Employee getEmp(@PathVariable("id") Integer id){return employeeService.getEmp(id);}@GetMapping("/emp")public Employee update(Employee employee){employeeService.updateEmp(employee);return employee;}@GetMapping("/delEmp/{id}")public String delete(@PathVariable("id") Integer id){employeeService.deleteEmp(id);return "success";}@GetMapping("/emp/lastName/{lastName}")public Employee getEmpByLastName(@PathVariable("lastName") String lastName){return employeeService.getEmpByLastName(lastName);}
}

8.修改启动类

package com.laoxu.springboot;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@MapperScan("com.laoxu.springboot.mapper")
@EnableCaching//启用缓存
@SpringBootApplication
public class SimpleCacheApplication {public static void main(String[] args) {SpringApplication.run(SimpleCacheApplication.class, args);}}

9.创建自定义key生成器

package com.laoxu.springboot.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;@Configuration
public class MyCacheConfig {@Bean("myKeyGenerator")public KeyGenerator keyGenerator(){return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... objects) {String key=method.getName()+"["+ Arrays.asList(objects).toString()+"]";return key;}};}
}

10.反复执行以下测试路径,观察console的日志输出

查看resources文件夹下的readme.txt文件。、

#查询
http://localhost:8080/emp/1
http://localhost:8080/emp/2
#更新
http://localhost:8080/emp?id=1&lastName=%E5%BC%A0%E4%B8%892&email=zhangsan1@1.com&gender=1&dId=1
#删除
http://localhost:8080/delEmp/1
#测试更新
http://localhost:8080/emp?id=1&lastName=%E5%BC%A0%E4%B8%891&email=zhangsan1@1.com&gender=1&dId=1

spring boot使用自带缓存相关推荐

  1. Spring Boot 集成 Redis 实现缓存机制

    本文章牵涉到的技术点比较多:spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对以上这些技术点有一定的了解或者也可以先看看这篇文章 ...

  2. Spring Boot 整合Redis 实现缓存

    本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 运行环境 ...

  3. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 一.缓 ...

  4. 注解参数获取不到_scm-springboot基于spring boot的统一注解缓存

    scm-springboot 基于spring boot的统一注解缓存,支持mencached.redis.ehcache的缓存无缝切换.支持单个缓存设置过期时间,灵活的key设置规则,采用fastj ...

  5. 第 4-4 课:Spring Boot 中使⽤ Cache 缓存的使⽤

    我们知道绝⼤多数的⽹站/系统,最先遇到的⼀个性能瓶颈就是数据库,使⽤缓存做数据库的前置缓存,可以 ⾮常有效地降低数据库的压⼒,从⽽提升整个系统的响应效率和并发量. 以往使⽤缓存时,通常创建好缓存⼯具类 ...

  6. 在Spring Boot中使用数据缓存

    关注公众号[江南一点雨],专注于 Spring Boot+微服务以及前后端分离等全栈技术,定期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货! 春节就要到了,在回家之前要 ...

  7. Java Web现代化开发:Spring Boot + Mybatis + Redis二级缓存

    背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybatis是一个十分轻量好用的ORM框架.Redis是当今十分主流的分布式key- ...

  8. Spring Boot下的Redis缓存实战

    最近在做的一个系统涉及到基础数据的频繁调用,大量的网络开销和数据读写给系统带来了极大的性能压力,我们决定引入缓存机制来缓解系统压力. 什么是缓存 提起缓存机制,大概10个程序员总有5种不同的解释吧(姑 ...

  9. caffeine_使用Caffeine和Spring Boot的多个缓存配置

    caffeine 缓存是几乎所有应用程序性能的关键. 有时需要分布式缓存,但并非总是如此. 在许多情况下,本地缓存可以很好地工作,并且不需要分布式缓存的开销和复杂性. 因此,在许多应用程序中,包括普通 ...

最新文章

  1. 力扣(LeetCode)刷题,简单题(第3期)
  2. 推荐算法工程师的成长之道
  3. 软件测试报告bug统计,软件测试中如何有效地写Bug报告
  4. ubuntu 只有客人会话登录(第一次深刻感受文件权限的威力 )
  5. 合约 cd 模式_CD的完整形式是什么?
  6. java 泛型 父子_使用通配符和泛型:完成父子类关系的List对象的类型匹配
  7. iReport报表工具的使用
  8. 为什么spyder这么慢_微区成分分析为什么这么慢?
  9. SharePoint2010内容类型剖析(三)
  10. 论文笔记_S2D.55_2019_SLAM综述_Huang B. A Survey of Simultaneous Localization and Mapping
  11. 社会工程学之《反欺骗的艺术》小结(一)
  12. VS2015 C#程序打包成.exe之installshield使用教程
  13. 【预测模型】Logistic 人口阻滞增长模型
  14. linux的fseek函数
  15. 人工智能粒子群优化和群智能
  16. c语言中元音字母对应的的值,c语言输入一个字符串,统计这个字符串的元音字母...
  17. 2020年诺贝尔化学奖得主自述:基因编辑技术将把我们带向何方?
  18. 单片机数码管显示实操
  19. 【内网安全】——数据库提权姿势
  20. c语言患者住院管理系统,住院系统-中小医院医疗套装软件管理系统_九明珠信息科技...

热门文章

  1. SAP ABAP ME2L/ME2N/ME28添加客制化字段 BADI ME_CHANGE_OUTTAB_CUS
  2. linux创建c文件编译错误,gcc已安装,编译其他软件时提示c编译器无法创建可执行文件...
  3. 汉文博士 0.5.6.2345 修订版发布
  4. Python 从源码到执行
  5. Open Policy Agent: Top 5 Kubernetes 准入控制策略
  6. 无人商店是“风口”吗? 风险与机遇并存!
  7. 文件编码H264编解码器性能测试
  8. 【matcovnet学习笔记】objective,top1error,top5error详解
  9. Linux进程互斥——临界资源访问
  10. 测试用例管理工具比较