开发者学堂课程【SpringBoot 实战教程: SpringBoot 整合 Redis(单机版)】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/651/detail/10813
SpringBoot 整合 Redis(单机版)
1、首先进行架包依赖,以下是 springboot 提供的 redis 的依赖。把它加入工程中。
<!--springboot 整合 redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
现在的工程是 springboot 整合 mybatis 的案例,在这个案例上加入缓存的使用,首先加入依赖,然后配置 redis 的相关配置和端口号,在全局配置中加入即可。
#redis 单服务器配置
spring.redis.database=0
向 redis 第一个数据库进行存储
spring.redis.host=192.168.25.128
单机版 redis 所在服务器的地址
spring.redis.port=6379
redis 端口号
spring.redis.pool.max-active=8 性能的配置
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0
redis 是在 linux 下,启动,端口号是6379,查看电脑 ip 地址,linux@ubuntu:~$ ifconfig,是192.168.25.128。
2、在程序中 redis 缓存如何使用?
(1)首先开启缓存,在启动类上输入:
@EnableCaching/ / 开启缓存
(2)在查询里面使用缓存,从数据库查询的数据放到缓存中,下次用时直接从缓存中取即可。在 service 里面有一个添加用户的,有一个查找用户的,在查找功能上加入缓存,根据用户的姓名查找用户,用注解 Cacheable 加入缓存,redis 存储的数据是键值对的方式,把它根据姓名查询出的用户,把它放入 redis 缓存。
@Autowired
private UsersMapper usersMapper;
@Cacheable(value= "myname‘’)指定键
@Override
public Users
findUserByName (String name) { 第一次调用功能它会从数据库中查询,第二次它会从缓存中取,不会进行打印
System. out. println ("从数据库中查询...‘’);证明缓存
return use rsMapper . findByName (hame) ;用户的信息相当于值
}
3、启动,单机版直接用注解就可以解决,比较简单,访问 controller,从数据库找一个人,启动客户端,点击 db1数据库,users,搜索查询小红,localhost:8080/findUserByName?name=小红,出现错误。
控制台提示无效参数异常,它需要序列化的 users 对象。
Defaul tserializer requires a Serial izable payload but received an object of type [ com. db1.pojo.Users]
在 users.java 中输入
public class Users implements Serializable{
它需要序列化的实体类对象。
4、重新启动,刷新,第一次从数据库查,它没有使用缓存。
控制台打印出这句话。
再次访问是从缓存中查询,没有打印。这时使用了 redis 缓存。


