参数 – value : 缓存的名称,在 spring 配置文件中定义,必须指定至少一个
参数 – key : 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
参数 – condition : 缓存的条件,可以为空,使用 SpEL 表达式编写,返回 true 或者 false,只有为 true 才进行缓存
想必你一定想知道SpEL 表达式是什么,下面我们简单的介绍一下:
SpEL 表达式:Spring 3引入了Spring表达式语言( Spring Expression Language,SpEL),它能够以一种强大和简洁的方式将值装配到bean属性和构造器参数中,在这个过程中所使用的表达式会在运行时计算得到值
更深入的了解请点击这里,SpEL 表达式深入理解
@Cacheable的语法 :
@Cacheable(value=”缓存的名称”,key=”#xxx”)
redis命令行客户端使用hset的语法是:
hset key field value
使用@Cacheable注解,调用的是redis的set函数,生成的value和key用::来进行连接,结果如下图:
测试类试试:
创建一个service:
package com.tanhua.server.test;
import com.tanhua.model.db.UserInfo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserInfoCacheService {
//根据id查询
@Cacheable(value = "user",key = "#userId")
public UserInfo queryById(Long userId) {
//从数据库查询
System.out.println("从数据库查询");
UserInfo user = new UserInfo();
user.setId(userId);
user.setNickname("ceshi");
return user;
}
}
创建测试类:
package com.tanhua.server.test;
import com.tanhua.server.AppServerApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = AppServerApplication.class)
@RunWith(SpringRunner.class)
public class CacheTest {
@Autowired
private UserInfoCacheService userInfoCacheService;
@Test
public void test1() {
for (int i = 1; i <= 5; i++)
System.out.println(userInfoCacheService.queryById(1l));
}
}
第一次执行的结果:
第二次执行的结果:
从这里我们可以看出,数据已经进行缓存了,而redis中生成了一个文件,文件结构如图:
user是value 1则是key
如有错误请指正