加入依赖
<!--集成Redis缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件配置相关参数
####Redis配置########################
#默认redis数据库为db0
spring.redis.database=0
#服务器地址,默认为localhost
spring.redis.host=localhost
#连接端口 默认6379
spring.redis.port=6379
#redis默认密码空
spring.redis.password=
Redis的使用,初步体验:Listener监听器加载时使用
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized========Redis存储所有用户信息");
List<AyUser> list=ayUserService.findAll();
redisTemplate.delete(ALL);
redisTemplate.opsForList().leftPushAll(ALL,list);
//测试一下 ,获取数据
List<AyUser> list1=redisTemplate.opsForList().range(ALL,0,-1);
System.out.println(list.size()+"个数");
}
运行成功则打印相关信息嘛,此种有个要点,当我们数据存放到Redis时,键值都是通过Spring提供的Serializer序列化到数据库的。因此我们需要让实体类实现序列化接口Serializable,否则将扔出非法异常
Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.demo.model.AyUser]
因此 实体类实现一下序列化接口即可。
缓存直接占用了内存容量,因此不可以乱用。