SpringBoot2.x.x版本+redis的缓存实现
前提条件:需要有redis数据库服务,本机位置或者远程服务器主机上
1.首先加入对应的jar包(主要的jar依赖如下):
<!--开启 cache 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 使用redis作为缓存数据区域 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在application.yml文件中配置对应的redis的相关配置内容:
#配置redis
spring:
cache:
type: REDIS
cache-names: redis_cache , ehcache #缓存的名字
redis:
time-to-live: 60000 #很重要,缓存的有效时间,以便缓存的过期(单位为毫秒)
redis:
host: 127.0.0.1 #对应redis所在的IP地址
port: 6379 #redis数据库对应的端口号
database: 0 #使用第1个数据库,一共默认有16个(0-15)
jedis: #一些常规配置
pool:
max-idle: 60
min-idle: 30
max-wait: 60000
max-active: 200
3.在SpringBoot的启动类上加上@EnableCaching 注解即可
4.需要使用的缓存方法示例:
// @Cacheable(cacheNames={"redis_cache"},key="#no") //可正常成功执行 但no参数值必须传值否则会报异常
@Cacheable(cacheNames={"redis_cache"},keyGenerator="defineKeyGenerator")//no参数值可以不传,则对应的key值为null
public Student getStudentByNo(Integer no)
{
System.out.println("进入缓存方法...");
Student stu=null;
if(no==null)
stu=new Student(0,"Zero","零专业","零大学");
else
{
List<Student> stus=new ArrayList<>();
Student s1=new Student(1,"One","MOne","UOne");
Student s2=new Student(2,"Two","MTwo","UTwo");
Student s3=new Student(3,"Three","MThree","UThree");
stus.add(s1);
stus.add(s2);
stus.add(s3);
if(no>2)
no=2;
stu=stus.get(no);
}
return stu;
}
*** DefineKeyGenerator的类定义如下(有坑):
@Component
public class DefineKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... args) {
if(args==null)
return method.getName();
else
{
StringBuilder sb=new StringBuilder();
for(int i=0;i<args.length;i+=1)
{
String value=String.valueOf(args[i]);
sb.append(value);
}
return sb.toString();
}
}
}
generate:方法的返回值决定了缓存中所对应的key的值(若需要缓存方法(getStudentByNo)的返回结果与参数值有关,建议参数值不同时该方法(generate)的返回值也不同),若是使用方法名之类的值作为(generate)的返回值
,则会出现传入不同的参数值,但返回的结果却是相同(方法不再执行,而是从缓存中获取值)
5.运行结果示例图:
执行之前:
执行一次:
再次执行相同的方法在缓存的有效时间内,目标方法将不再被执行,而是直接从缓存中获取相应的值。