一. 项目整合
1. pom文件依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 高版本redis的lettuce需要commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2. redis配置类
/**
* @author: hejr
* @desc: Redis配置类
* @date: 2019/4/9 16:26
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认的jdkSerializeable序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
3. application.xml配置
server:
port: 8096
# Redis配置
spring:
redis:
database: 0
host: 127.0.0.1
jedis:
pool:
#最大连接数据库连接数,设 0 为没有限制
max-active: 8
#最大等待连接中的数量,设 0 为没有限制
max-idle: 8
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
max-wait: -1ms
#最小等待连接中的数量,设 0 为没有限制
min-idle: 0
lettuce:
pool:
max-active: 8
max-idle: 8
max-wait: -1ms
min-idle: 0
shutdown-timeout: 100ms
password: ''
port: 6379
4. 新建redisUtil工具类
/**
* @author: hejr
* @desc: Redis工具类
* @date: 2019/4/9 16:30
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
/**
* 添加字符串KEY
* @param key 字符串KEY
* @param value 值 可以为对象
* @param expire 过期时间
* @param timeUnit TimeUnit中定义的时间单位
*/
public void addKey(String key, Object value, long expire, TimeUnit timeUnit) {
this.redisTemplate.opsForValue().set(key, value, expire, timeUnit);
}
/**
* 根据KEY获取VALUE
*
* @param key
* @return value
*/
public Object getValue(String key) {
return this.redisTemplate.opsForValue().get(key);
}
}
二. 演示
1. 单元测试类
/**
* @author: hejr
* @desc:
* @date: 2019/4/9 16:35
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisUtilTest {
@Autowired
private RedisUtil redisUtil;
@Test
public void addKey() {
this.redisUtil.addKey("userName", "何金荣", 60, TimeUnit.SECONDS);
System.out.println("添加成功");
}
@Test
public void getKey() {
String value1 = (String) this.redisUtil.getValue("userName");
System.out.println("获取到key为userName的值:" + value1);
}
}
三. 源码下载
https://gitee.com/hejr.cn.com/SpringBoot2.0_2019/tree/master/springboot2_007