SpringBoot整合redis
一、概述
-
Redis是一中运行在内存的数据库,支持7种数据类型的存储。
-
Redis是以一种键值数据库,而且是一种以字符串类型为中心的,支持多种类型(字符串、数列、列表、集合、有序集合、基数、地理位置)
-
Key-value型:值可以是字符串(string)哈希(hash)列表(list)集合(sets)有序集合(sorted sets)。
二、本机启动redis
- (1)在Windows中下载redis压缩包,将文件解压,打开cmd窗口,运行cd切换到解压目录下,进入redis中,运行命令:redis-server.exe
redis.windows.conf - (2)另开一个cmd窗口,切换到redis目录下,运行:redis-cli.exe ,设置key-Value 。
三、SpringBoot+Mybatis整合redis
- 在springboot+mybatis整合从MySQL数据库中查询到数据库的基础上进行整合集成redis。
(1)添加pom.xml文件中的集成redis配置:
<!-- 整合Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
(2)在application.properties中配置:
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
#redis
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.maxTotal=8
spring.redis.pool.maxWaitMillis=1000
spring.redis.timeout=60000
(3)在serviceimpl层中的操作类进行添加RedisTemplate方法,然后进行查询
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Override
public List<Tuser> getAllUser() {
List<Tuser> tuserList =(List<Tuser>)redisTemplate.opsForValue().get("alluser");
if(null == tuserList) {
tuserList = tuserMapper.getAllUser();
redisTemplate.opsForValue().set("alluser", tuserList);
}
return tuserList;
(4)打开mysql数据库,然后在本机开启redis服务,同时打开redis可视化工具,进行运行项目,查询出mysql数据同时,打开Redis可视化工具,查看到mysql中的数据缓存到了redis中。