1.下载安装redis
https://blog.youkuaiyun.com/qq_42014192/article/details/88838597
2.新建一个springboot项目
https://blog.youkuaiyun.com/qq_42014192/article/details/88742559
3.添加redis相关依赖
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
4.application.properties文件中配置redis
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
5.创建实体
public class User {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public User() {
}
}
6.自动根据方法生成缓存
package com.example.springboot_redis_demo.controller;
import com.example.springboot_redis_demo.been.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=new User("aa@126.com", "aa");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}
}
7.启动springboot,访问http://localhost:8080/getUser
java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.example.springboot_redis_demo.been.User]
8.解决方案
https://blog.youkuaiyun.com/qq_42014192/article/details/88839621
9.运行结果:
第一次访问:进入controller将对象往redis数据库存入一份数据
第二次访问:无反应说明没有进入controller,直接从redis获取数据