1. 引入maven坐标
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce pool 连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2. 增加Redis配置信息(application.properties)
# redis数据库索引(默认为0)
spring.redis.database=0
# redis服务器地址
spring.redis.host=localhost
# redis服务器连接端口
spring.redis.port=6379
# redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(负值表示无限制,默认为8)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(负值表示无限制,默认为-1)
spring.redis.lettuce.pool.max-wait=-1
# 连接池最大空闲连接 默认为8
spring.redis.lettuce.pool.max-idle=8
# 连接池最小空闲连接 默认为0
spring.redis.lettuce.pool.min-idle=0
3. 配置类RedisConfig
package com.redistest.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
* 描述:
* 配置类
*
* @author XueGuCheng
* @create 2020-08-15 23:47
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory){
RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
4. 加入工具类RedisUtils
此步骤已省略,不影响简单测试。
5. 测试
测试前先检测Redis服务端是否已经启动
package com.redistest.demo;
import com.redistest.vo.User;
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.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 描述:
* 测试
*
* @author XueGuCheng
* @create 2020-08-16 0:26
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class test {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test01(){
User user = new User(1, "zhangsan", "nan");
ValueOperations operations = redisTemplate.opsForValue();
operations.set("jbp001",user);
Boolean flag = redisTemplate.hasKey("jbp001");
User getUser = (User) redisTemplate.opsForValue().get("jbp001");
System.out.println(flag);
System.out.println(getUser.toString());
}
}