SpringBoot整合Redis
一、起步依赖
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、application.properties中配置连接信息
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
三、注入测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisTemplateTest {
@Autowired
private UserRepository userRepository;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void test() throws Exception {
String userStr = redisTemplate.boundValueOps("user.findAll").get();
if (userStr == null) {
List<User> list = userRepository.findAll();
ObjectMapper om = new ObjectMapper();
userStr = om.writeValueAsString(list);
redisTemplate.boundValueOps("user.findAll").set(userStr);
System.out.println("~~~~~~~~~~ 从数据库中获取数据 ~~~~~~~~~~~~");
} else {
System.out.println("~~~~~~~~~~ 从Redis中获取数据 ~~~~~~~~~~~~");
}
System.out.println(userStr);
}
}