1.添加Redis的起步依赖
<!-- 因为要使用JSON,额外导入web的起步依赖,其中包含了JSON -->
<!-- web功能的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.启动Redis服务器
3. 在SpringBoot配置文件中配置redis的连接信息
# Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
4.创建实体Bean
package com.atlantis.domain;
public class User {
private Integer id;
private String username;
private String password;
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
//省略getter、setter和toString方法 .. ..
}
5.注入RedisTemplate测试Redis操作
package com.atlantis;
import com.atlantis.domain.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartSpringBootApplication.class)
public class RedisTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void test() throws JsonProcessingException {
// 从Redis缓存中获得指定的数据
String userListData = redisTemplate.boundValueOps("user.findAll").get();
// 如果Redis中没有数据
if (null == userListData) {
// 模拟从数据库获取数据
List<User> users = new ArrayList<>();
users.add(new User(1, "Atlantis", "123"));
users.add(new User(2, "Olivia", "123"));
// 转换成JSON格式字符串
ObjectMapper om = new ObjectMapper();
userListData = om.writeValueAsString(users);
// 将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
redisTemplate.boundValueOps("user.findAll").set(userListData);
System.out.println("从数据库获得数据==================");
} else {
System.out.println("从Redis缓存中获得数据===============");
}
System.out.println(userListData);
}
}
6.运行结果
第一次运行,Redis中没有数据,此时会从数据库获取数据,并且将数据存储在Redis中,方便下次获取:
第二次运行,此时Redis中存在数据,则直接从Redis中获取数据: