您的位置:首页 > 数据库 > Redis

Spring Boot cache backed redis

2017-04-11 00:00 483 查看
摘要: Spring Boot cache backed redis

在应用部署多实例时,使用本地缓存(guava/caffeine)会造成数据不一致,所以需要采用集中的存储,此处使用redis。

0. 添加相关依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>${v}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${v}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${v}</version>
</dependency>

1. 添加相关配置

spring:
redis:
host: ${host}
port: ${port}

2. 开启缓存,在Application类加入@EnableCaching

3. 通过@Cacheable使用缓存

@Cacheable("{cacheNames}")
public Object needCache() {
return ...;
}


二. 指定缓存参数[以过期时间为例,不同的数据类型要求的缓存时间不同]

0. 配置不同过期时间Cache

@EnableCaching
@Configuration
public class CacheConfig {

@Autowired
private RedisTemplate<Object, Object> redisTemplate;

/**
* Define cache strategy
*
* @return CacheManager
*/
@Bean
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
Map<String, Long> expires = new HashMap<>();

// Test expires[1min]
expires.put("10S", 10L);

redisCacheManager.setExpires(expires);

return redisCacheManager;
}

}

1. 使用指定Cache

@Cacheable("10S")


PS:spring-gs-cachingspring-data-redis reference
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cache spring boot