解决方法是在springboot启动类上添加@EnableCaching注解
注: 在使用缓存时 实体类要实现Serializable接口 进行序列化
@EnableCaching
@SpringBootApplication
public class CacheRedisApplication {
public static void main(String[] args) {
SpringApplication.run(CacheRedisApplication.class, args);
}
首先是配置文件
spring.redis.host=localhost
spring.redis.database=0
spring.redis.port=6379
spring.cache.cache-names=c1
service层代码
@Service
public class UserService {
//开启允许缓存,缓存的key就是方法名,value是返回值 cacheNames的值是配置文件中配置的名称
//spring.cache.cache-names=c1
@Cacheable(cacheNames = "c1")
public User getUserById(Integer id){
System.out.println("getUserById>>>" +id);
User user = new User();
user.setId(id);
return user;
}
}
测试类
@SpringBootTest
class CacheRedisApplicationTests {
@Autowired
UserService userService;
@Test
void contextLoads() {
//调用两次service层方法 当没有缓存时会执行两次方法 创建两次对象,当实现缓存时只创建一次对象
//当检测到传递参数相同时去redis中获取数据
User user1 = userService.getUserById(1);
User user2 = userService.getUserById(1);
System.out.println(user1);
System.out.println(user2);
}
}
测试输出
getUserById>>>1
User{id=1, username='null', address='null'}
User{id=1, username='null', address='null'}
当没有添加@EnableCaching注解时 @Cacheable(cacheNames = "c1")不起作用