- Spring Cache介绍
- Spring Cache常用注解
- Spring Cache使用方式
- 代码举例
- (1)建表语句:
- (2)项目结构如下图:
- (3)pom文件:
- (4)controller层:UserController
- (5)Service层: UserService 接口
- (6)Mapper层:UserMapper
- (7)resource 中的yaml文件:
- (8)主启动类:
Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。
CacheManager是Spring:提供的各种缓存技术抽象接口。
针对不同的缓存技术需要实现不同的CacheManager:
| CacheManager | 秒睡 |
|---|---|
| EnCacheManager | 使用EnCache作为缓存技术 |
| GuavaCacheManager | 使用Google的GuavaCache作为缓存技术 |
| RedisCacheManager | 使用Redis作为缓存技术 |
| 注解 | 说明 |
|---|---|
| @EnableCaching | 开启缓存注解功能 |
| @Cacheable | 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 |
| @CachePut | 将方法的返回值放到缓存中 |
| @CacheEvict | 将一条或多条数据从缓存中删除 |
在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。
Spring Cache使用方式
在Spring Boot]项目中使用Spring Cache的操作步骤(使用redis缓存技术):
- 导入maven坐标spring-boot-starter-data-redis,spring-boot-starter-cache
- 配置application.yml
- 在启动类上加入@EnableCaching注解,开启缓存注解功能
- 在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作
第1条中的依赖如下:
org.springframework.boot
spring-boot-starter-data-redis
2.7.0
org.springframework.boot
spring-boot-starter-cache
2.7.0
第2条中yaml文件插入如下:
spring:
application:
#应用的名称,可选
name: take_out
redis:
host: 127.0.0.1
port: 6379
database: 0
cache:
redis:
time-to-live: 180000 #设置缓存有效期
代码举例
创建数据库cache_demo,在其中建立一个表user
(1)建表语句:SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROp TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL, `name` char(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;(2)项目结构如下图:
(4)controller层:UserController4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.5 org.example test 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-web compile org.projectlombok lombok 1.18.20 com.alibaba fastjson 1.2.76 commons-lang commons-lang 2.6 mysql mysql-connector-java runtime com.baomidou mybatis-plus-boot-starter 3.4.2 com.alibaba druid-spring-boot-starter 1.1.23 org.springframework.boot spring-boot-maven-plugin 2.4.5
package com.rzn.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rzn.entity.User;
import com.rzn.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private CacheManager cacheManager;
@Autowired
private UserService userService;
//@CachePut(value = "userCache",key = "#result.id")
@CachePut(value = "userCache",key = "#user.id")
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
//写法不同,但是效果或者说是实现的目的是相同的
//@CacheEvict(value = "userCache", key = "#id")
//@CacheEvict(value = "userCache", key = "#p0")
@CacheEvict(value = "userCache", key = "#root.args[0]")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
//@CacheEvict(value = "userCache",key = "#p0.id")
//@CacheEvict(value = "userCache",key = "#user.id")
//@CacheEvict(value = "userCache",key = "#root.args[0].id")
@CacheEvict(value = "userCache",key = "#result.id")
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
@Cacheable(value = "userCache", key = "#id", condition = "#result!=null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
@Cacheable(value = "userCache", key = "#user.id+'_'+#user.name")
@GetMapping("/list")
public List list(User user){
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(user.getId() != null,User::getId,user.getId());
queryWrapper.eq(user.getName() != null,User::getName,user.getName());
List list = userService.list(queryWrapper);
return list;
}
}
(5)Service层: UserService 接口
package com.rzn.service; import com.baomidou.mybatisplus.extension.service.IService; import com.rzn.entity.User; public interface UserService extends IService{ }
UserServiceImpl实现类:
package com.rzn.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.rzn.entity.User; import com.rzn.mapper.UserMapper; import com.rzn.service.UserService; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl(6)Mapper层:UserMapperimplements UserService { }
package com.rzn.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.rzn.entity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper{ }
entity实体包:User类
package com.rzn.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private int age;
private String address;
}
(7)resource 中的yaml文件:
server:
port: 8080
spring:
application:
#应用的名称,可选
name: cache_demo
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123456
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
(8)主启动类:
package com.rzn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
注意观察controller中的方法上的注解,还有主启动类上的注解。
谢谢阅读,无误点赞,有误还望评论区指正。



