0004SpringBoot整合Redis

在已经整合了SpringDataJPA和Junit的基础上,整合Redis,只需要一下几步即可:

1、下载64windows版的Redis安装包、解压并启动服务端

2、配置Redis的起步依赖(pom.xml)

3、配置连接Redis服务器的信息(application.propertis)

4、写测试类

5、启动测试

具体内容如下:

下载64windows版的Redis安装包、解压并启动服务端

下载地址为:

https://github.com/MicrosoftArchive/redis/releases

下载64位的版本,如下图:

 

解压后:

双击redis-server.exe即可启动redis服务端

双击redis-cli.exe即可启动redis客户端

pom.xml中配置Redis的起步依赖:

<!--redis的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.properties中配置连接redis服务器的信息:

# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379

编写测试类:

package com.myself;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myself.domain.User;
import com.myself.repository.UserRepository;
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 = SpringbootJpaApplication.class)
public class RedisTest {
@Autowired
private RedisTemplate<String,String> redisTemplate;

@Autowired
private UserRepository userRepository;

@Test
public void queryUsers() throws JsonProcessingException {
//从redis缓存中查询数据,redis是nosql的K-V键值对,所以设置键为user.findAll
        String listUserJson = redisTemplate.boundValueOps("user.findAll").get();
//如果数据为空,则为首次访问,需要从数据库中查询数据
if(listUserJson == null){
       //从数据库中查询数据
List<User> users = userRepository.findAll();
//将数据转换为json字符串,由于我们配置了web的起步依赖,所以我们可以使用Jackson进行数据转换
       //jackson中的对象
ObjectMapper objectMapper = new ObjectMapper();
listUserJson = objectMapper.writeValueAsString(users);
redisTemplate.boundValueOps("user.findAll").set(listUserJson);
System.out.println("=================从数据库中查询数据=============================================");
}else{
System.out.println("=================从redis缓存中查询数据=============================================");
}
System.out.println("user数据为:" + listUserJson);

}

}

如有理解不到位之处,望指正。

猜你喜欢

转载自www.cnblogs.com/xiao1572662/p/11876239.html
今日推荐