1.redis起步依赖
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在application.preperties中配置连接信息
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
3.测试redis操作
package com.itheima;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.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;
/**
* @author boyi on 2019/12/8
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootMybatisApplication.class)
public class RedisTest {
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void test() throws JsonProcessingException {
//1.从redis中获取数据,json的字符串
String userListJson = redisTemplate.boundValueOps("user.findAll").get();
//2.判断Redis中是否存在数据
if(null==userListJson) {
List<User> all = userMapper.queryUserList();
//4.将查询出的数据存储到redis缓存中
ObjectMapper objectMapper = new ObjectMapper();
userListJson = objectMapper.writeValueAsString(all);
redisTemplate.boundValueOps("user.findAll").set(userListJson);
System.out.println("从数据库中获取数据=============");
} else {
System.out.println("从redis缓存中获得数据==========");
}
System.out.println(userListJson);
}
}
4.结果演示
这是第二次运行
可以看出,我们的redis整合成功了。
来源:CSDN
作者:暴力小气球
链接:https://blog.csdn.net/weixin_43287478/article/details/103473438