1.pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2.yml配置
# redis 配置redis:host: 127.0.0.1#超时连接timeout: 1000msjedis:pool:#最大连接数据库连接数,设 0 为没有限制max-active: 8#最大等待连接中的数量,设 0 为没有限制max-idle: 8#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。max-wait: -1ms#最小等待连接中的数量,设 0 为没有限制min-idle: 0
3.redis配置
/*** Redis 配置*/
@Configuration
public class RedisConfig {private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;/*** 序列化配置*/@Beanpublic RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {LOGGER.info("RedisConfig == >> redisTemplate ");RedisTemplate<String, Serializable> template = new RedisTemplate<>();template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}
}
4.在redis中添加数据
@Resourceprivate StringRedisTemplate stringRedisTemplate ;@RequestMapping("/setGet")public String setGet (){stringRedisTemplate.opsForValue().set("cicada","smile");return stringRedisTemplate.opsForValue().get("cicada") ;}
5.设置Key的过期时间
@Resourceprivate RedisTemplate redisTemplate ;/*** 设置 Key 的有效期 10 秒*/@RequestMapping("/setKeyTime")public String setKeyTime (){redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);return "success" ;}@RequestMapping("/getTimeKey")public String getTimeKey (){// 这里 Key 过期后,返回的是字符串 'null'return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;}
}
6.在Redis中添加对象
@Resourceprivate RedisTemplate redisTemplate ;@RequestMapping("/setUser")public String setUser (){User user = new User() ;user.setName("cicada");user.setAge(22);List<String> list = new ArrayList<>() ;list.add("小学");list.add("初中");list.add("高中");list.add("大学");user.setEducation(list);redisTemplate.opsForValue().set("userInfo",user);return "success" ;}
从redis中获取对象