项目地址: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.Driver
username: root
password: root123
url: jdbc:mysql://localhost:3306/spring_cache?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT&useSSL=false mybatis:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl debug: true #redis

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

/*
Navicat MySQL Data Transfer Source Server : 本地
Source Server Version : 50528
Source Host : 127.0.0.1:3306
Source Database : springboot_cache Target Server Type : MYSQL
Target Server Version : 50528
File Encoding : 65001 Date: 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;
}
@Override
public 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;
}
@Override
public 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 {
@Autowired
EmployeeMapper 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 {
@Autowired
EmployeeService 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() {
@Override
public 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 + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

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

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

  3. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

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

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

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

    春节就要到了,在回家之前要赶快把今年欠下的技术债还清.so,今天继续.Spring Boot前面已经预热了n篇博客了,今天我们来继续看如何在Spring Boot中解决数据缓存问题.本篇博客是以初识在 ...

  6. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  7. Spring Boot 整合Redis 实现缓存

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

  8. spring boot学习(十三)SpringBoot缓存(EhCache 2.x 篇)

    SpringBoot 缓存(EhCache 2.x 篇) SpringBoot 缓存 在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManag ...

  9. Spring Boot集成EHCache实现缓存机制

    SpringBoot 缓存(EhCache 2.x 篇) SpringBoot 缓存 在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManag ...

  10. Spring Boot:使用Memcached缓存

    综合概述 Memcached是一个自由开源的,高性能,分布式内存对象缓存系统.Memcached基于内存的key-value存储,用来存储小块的任意数据,这些数据可以是数据库调用.API调用或者是页面 ...

随机推荐

  1. unix domain 与本地本地回环在进程间通信中的差异

    前言: 127.0.0.1它是一个私有IP,代表的就是你的本机环回地址,其实本质上是绑定在虚拟网卡loopback上的IP. 在实际应用中,有遇到在使用本地回环做进程间通讯的时候程序阻塞的情况.比如下 ...

  2. MySQL 8.2.0部署安装验证

    MySQL 8.2.0部署安装验证 背景 昨天捯饬了半天Oracle23c Free版本发现自己白忙活了. 然后想着继续看一下 MySQL8.2. 看看会不会又继续白忙活 下载与安装 https:// ...

  3. Oracle process/session/cursor/tx/tm的简单学习

    Oracle process/session/cursor/tx/tm的简单学习 Oracle的部署模式 Oracle安装时有专用模式和共享模式的区别 共享模式(Shared mode): 在共享模式 ...

  4. [转帖]RocketMQ - nameSrv和Broker

    RocketMQ RocketMQ是一个统一的消息传递引擎,轻量级的数据处理平台. Name Server Name Server充当路由消息的提供者,生产者(Producer)或消费者(Custom ...

  5. [转帖]详解:Linux Chrony 设置服务器集群同步时间

    https://www.linuxprobe.com/centos7-chrony-time.html 导读 Chrony是一个开源的自由软件,像CentOS 7或基于RHEL 7操作系统,已经是默认 ...

  6. [转帖]5.2. 使用HINT

    ¶ 本章节包含以下内容: 概述 HINT的功能 HINT的使用 配置参数 示例 注意 5.2.1. 概述 ¶ KingbaseES使用的是基于成本的优化器.优化器会估计SQL语句的每个可能的执行计划的 ...

  7. [转帖]金仓数据库KingbaseES表空间介绍

    1.表空间的概念 KingbaseES中的表空间允许在文件系统中定义用来存放表示数据库对象的文件的位置.在KingbaseES中表空间实际上就是给表指定一个存储目录. 2.表空间的作用 通过使用表空间 ...

  8. [转帖]创建lvm

    https://www.jianshu.com/p/bf6b92d73b9b 一.环境介绍 服务器中有sda,sdb,sdc,sdd,sde,sdf六块硬盘,其中sda作为系统盘已经安装了系统,需要将 ...

  9. 申威3231服务器Redis性能验证-及最全信创CPU性能分析

    申威3231服务器Redis性能验证-及最全信创CPU性能分析 背景 公司里面新进了几台服务器. 有台申威服务器. 因为前段时间参与过一次申威的POC验证. 当时对性能有一点简单的理解. 但是因为不方 ...

  10. 【转帖】MySQL 8.0.32如期而至

    MySQL 8.0版本计划 MySQL 8.0开始采用快速迭代开发模式,基本上是每隔3个月就发布一个新的小版本.去年1月18日(2022.1.18)发布MySQL 8.0.28,今年1月17日发布My ...