-
需要使用到的pom包
org.springframework.boot spring-boot-starter-data-redis 当然肯定你是默认使用的Spring boot 2.x项目
-
配置
spring: datasource: redis: host: localhost
-
在项目中使用
@Autowiredpublic Class RedisTemplate redisTemlate;// 缓存public Article getById(String id) { Article article = (Article) // 获取缓存 redisTemplate.opsForValue().get(ARTICLE_KEY + id); // 没有缓存就重新设置一个 if (article == null) { article = articleRepository.getOne(id); redisTemplate.opsForValue().set(ARTICLE_KEY + id, article); } return article;}// 删除public void deleted(String id) { redisTemplate.delete(ARTICLE_KEY + id); articleRepository.deleteById(id);}
除此之外如果想设置过期时间:
void set(K key, V value, long timeout, TimeUnit unit)
timeout
超时时间。unit
时间单位。有如下几个单位:
- NANOSECONDS: 千分之一微妙的时间单位
- MICROSECONDS: 千分之一毫秒的时间单位
- MILLISECONDS: 千分之一秒的时间单位
- SECONDS: 秒的时间单位
- MINUTES: 分的时间单位
- HOURS:小时的时间单位
- DAYS:天的时间单位