Springboot集成Redis
1. Redis本地安装
github下载地址:https://github.com/MSOpenTech/redis/tags
- 下载下来后解压后目录如下:
- 在当前目录启动cmd,使用命令
redis-server redis.windows.conf
出现下图:
到此,本地的redis启动成功
2. springboot集成redis
- 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
- 允许缓存机制
//启动类上添加该注解允许缓存
@SpringBootApplication
@EnableCaching
public class ObjectOrientedApplication {
public static void main(String[] args) {
SpringApplication.run(ObjectOrientedApplication.class, args);
}
}
//业务逻辑方法上加上注解
@Override
@Cacheable(value = "userCache",key = "'user.getAllUser'")
public List<User> getAllUser() {
return userMapper.getAllUser();
}
- 实体类实现序列化接口
@Data
public class User implements Serializable {
private static final long serial = 1L;
private String userId;
private String userName;
private String password;
private int playCount;
}
- 在application.properties添加redis配置
# redis
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
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=30000
- 启动项目,postman作接口测试
第一次调用,看到时间为1578ms
同时控制台打印出了相应的sql语句
第二次调用:可以看到时间缩短至 8ms
同时控制台没有给出任何输出
缓存成功
- 清除缓存
避免在更新数据库之后 ,缓存中内容与数据库中内容不一致导致业务逻辑出错
//在相应的delete方法上加上注解
@CacheEvict(value = "userCache",key = "'user.getAllUser'")