项目中Redis的好处
- 速度快,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1)
- 支持丰富数据类型,支持string,list,set,sorted set,hash
- 支持事务,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行
- 丰富的特性:可用于缓存,消息,按key设置过期时间,过期后将会自动删除
springboot中部署Redis
-
起步依赖
<!--redis起步依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
运行redis
先下载redis,直接运行里面的==redis-server.exe
-
配置数据库 mybatis和redis的yml
#数据库连接信息 spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/php?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT driver-class-name: com.mysql.cj.jdbc.Driver redis: host: 127.0.0.1 port: 6379 #配置mybatis信息 mybatis: type-aliases-package: com.springboot_redis.domain mapper-locations: classpath:mapper/*Mapper.xml
-
编写controller测试
package com.springboot_redis; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.springboot_redis.domain.User; import com.springboot_redis.mapper.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootRedisApplication.class) public class RedisTest { @Autowired private RedisTemplate<String, String> redisTemplate; @Autowired private UserMapper userMapper; @Test public void test() throws JsonProcessingException { //1、从redis中获得数据 数据的形式json字符串(因为存储也是用json) String userListjson = redisTemplate.boundValueOps("user.findAll").get(); //2、判断是否存在数据 if (null == userListjson) { //3、数据不存在 从数据库查询 List<User> userList = userMapper.getUser(); //4、将查询出的数据存储到redis缓存中(json格式) //将list集合转换成json格式 ObjectMapper objectMapper = new ObjectMapper(); userListjson = objectMapper.writeValueAsString(userList); redisTemplate.boundValueOps("user.findAll").set(userListjson); System.out.println("==========从数据库中获得user的数据============"); } else { //5、将返回数据在控制台打印 System.out.println("==========从redis中获得user的数据============"); } System.out.println(userListjson); } }
因为是第一次运行 所以没有缓存 出来的结果是从数据库获得数据
第二次运行会直接查询redis中的缓存