springboot+springCache+Redis声明式缓存

在springboot与Redis缓存使用时可以有多重方式使用,下面介绍其中的一种,声明式缓存也解释使用注解形式来操作Redis。

具体步骤如下:

1. 配置pom.xml(我的项目是maven工程)

<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>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>

2. 在application.yml 配置与Redis的链接信息(springboot的配置文件)

spring:
redis:
database: 9
host: 127.0.0.1
port: 6379
#password:
jedis:
pool:
max-active: 100
max-idle: 100
min-idle: 10
max-wait: 1000ms

3.在应用程序入口类 xxxApplication中开启springcache缓存

4.使用注解存储数据

  springcache常用注解

 @Cacheable 注解

      最常用的注解,会把注解方法的返回值缓存。工作原理:首先在缓存中查找,如果缓存中没有找到,则执行方法并将结果保存在缓存中,然后返回数据结果。此注解缓存名必须制定,和cacheManager中的caches中的某一个Cache的name值对应,可以使用value或cacheNames指定。

     如果没有key属性,spring会使用默认的主键生成器产生主键。也可以自定义主键,在key中可以使用spEL表达式

@CachePut注解

  先执行方法,然后将返回值放回缓存。可以用作缓存的更新。

@CacheEvict注解

  该注解负责从缓存中显式移除数据,通常缓存数据都有有效期,当过期时数据也会被移除。

  此注解多了两个属性:

    allEntries是否移除所有缓存条目。

    beforeInvocation:在方法调用前还是调用后完成移除操作。true/false

猜你喜欢

转载自www.cnblogs.com/binkai/p/9367407.html