快速入门:Spring Cache

简介: 快速入门:Spring Cache

一:Spring Cache简介

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要一个简单的注解,就能实现缓存功能。

Spring Cache提供了一层抽象,底层可以切换不同的缓存实现,例如: EHche Caffeine Redis.对应的不同缓存有不同的依赖。

二:Spring Cache常用注解

2.1:@EnableCaching

开启缓存注解功能,通常用在启动类上。

2.2: @Cacheable

在某个方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据value的值;如果没有缓存数据,调用方法并将返回值放到缓存中。

2.3:@CachePut

将方法的返回值放到缓存中。

2.4:@CacheEvict

将一条或多条数据从缓存中删除

三:Spring Cache案例

3.1:先在pom.xml中引入两个依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

3.2:案例

3.2.1:构建数据库表

create database spring_cache_demo;
use spring_cache_demo;
CREATE TABLE `user` (
                        `id` bigint NOT NULL AUTO_INCREMENT,
                        `name` varchar(45) DEFAULT NULL,
                        `age` int DEFAULT NULL,
                        PRIMARY KEY (`id`)
);

3.2.2:构建User类

@Data
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
    private int age;
}

3.2.3:构建Controller  mapper层代码

由于当前业务逻辑比较简单,所以我们不需要service层的代码

//Controller层
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }
    @DeleteMapping
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }
  @DeleteMapping("/delAll")
    public void deleteAll(){
        userMapper.deleteAll();
    }
    @GetMapping
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }
}
//mapper层代码
@Mapper
public interface UserMapper{
    @Insert("insert into user(name,age) values (#{name},#{age})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    void insert(User user);
    @Delete("delete from user where id = #{id}")
    void deleteById(Long id);
    @Delete("delete from user")
    void deleteAll();
    @Select("select * from user where id = #{id}")
    User getById(Long id);
}

3.2.4:在启动类上添加注解@EnableCaching

@Slf4j
@EnableCaching//代表开启注解
@SpringBootApplication
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}

3.2.5:使用剩余部分注解

当是插入操作时,我们考虑用哪个注解?

我们考虑使用的是@CachePut这个注解(原因:这个注解是将方法的返回值存储到缓存当中)。

@Autowired
    private UserMapper userMapper;
    @CachePut(cacheNames = "userCache",key ="#user.id")
    //如果使用springCache缓存数据,key的生成:userCache:
    @PostMapping
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

同时在mapper接口中,要加入user的id返回的注解,代码如下:

@Insert("insert into user(name,age) values (#{name},#{age})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    void insert(User user);

接口文档中进行测试:

Redis中进行查看:


当根据用户的id查询用户时,我们该使用哪个注解?

我们使用@Cacheable注解(在方法执行前,判断有没有缓存数据,如果有,直接进行返回,如果没有,则调用方法并将数据放到缓存当中)。

@GetMapping
    @Cacheable(cacheNames = "userCache", key="#id")
    //key的生成:userCache:id value:为查询相应的数据,若是查询到,直接进行返回,如果查询不到,则将其加入到缓存
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

当删除一条或者多条数据时,使用哪个注解?

这个比较简单,我们使用@CacheEvit注解(这个注解可以删除一条或者多条数据)。

@DeleteMapping
    @CacheEvict(cacheNames = "userCache",key="#id")
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }
  @DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries=true)
    public void deleteAll(){
        userMapper.deleteAll();
    }
相关文章
|
2月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
4月前
|
缓存 NoSQL Java
Spring Cache 缓存原理与 Redis 实践
Spring Cache 缓存原理与 Redis 实践
166 0
|
5月前
|
缓存 NoSQL Java
Spring Boot 3 整合 Spring Cache 与 Redis 缓存实战
Spring Boot 3 整合 Spring Cache 与 Redis 缓存实战
|
2月前
|
存储 XML 缓存
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南(一)
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南
79 0
|
2月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
5月前
|
缓存 NoSQL Java
Spring Cache
Spring Cache
19 0
|
5月前
|
缓存 Java 关系型数据库
Spring Boot与Spring中的数据缓存Cache支持与实战(附源码)
Spring Boot与Spring中的数据缓存Cache支持与实战(附源码)
49 0
Spring Boot与Spring中的数据缓存Cache支持与实战(附源码)
|
5月前
|
缓存 Java Maven
Spring Cache框架,实现了基于注解的缓存功能。
Spring Cache框架,实现了基于注解的缓存功能。
33 0
|
5月前
|
缓存 NoSQL Java
Spring Cache 整合 Redis 做缓存使用~ 快速上手~
Spring Cache 整合 Redis 做缓存使用~ 快速上手~
69 1
|
5月前
|
缓存 NoSQL Java
spring cache使用redis
spring cache使用redis
45 1