最近學習spring+redis來緩存數據,看得一些書籍和教程都是spring-data-redis1.x的版本,其中一些方法已通過時了,因此我整理了一下簡單的2.x的配置。
項目地址:https://github.com/ksyzz/spri...git
項目使用的是maven管理依賴github
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.3.RELEASE</version> </dependency>
導入spring-data-redis和redis.client的包。redis
建立一個配置類RedisConfig,爲該類添加@Configuration和@EnableCaching(啓用緩存)的註解。
若是想在spring的註解@Cacheaable使用redis緩存,關鍵在於自定義CacheManager的bean。
代碼以下:spring
@Configuration @EnableCaching public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; /** * 若是隻使用註解則不須要配置該bean * @param jedisConnectionFactory * @return */ @Bean public RedisTemplate initRedisTemplate(@Qualifier("connectionFactory") JedisConnectionFactory jedisConnectionFactory) { RedisSerializer str = new StringRedisSerializer(); RedisSerializer json = new GenericJackson2JsonRedisSerializer(); RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(jedisConnectionFactory); redisTemplate.setKeySerializer(str); redisTemplate.setValueSerializer(json); redisTemplate.setHashKeySerializer(str); redisTemplate.setHashValueSerializer(json); return redisTemplate; } @Bean(name = "connectionFactory") public JedisConnectionFactory initConnect(){ RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port); JedisConnectionFactory connectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration); connectionFactory.afterPropertiesSet(); return connectionFactory; } @Bean public CacheManager init(@Qualifier("connectionFactory") JedisConnectionFactory jedisConnectionFactory){ // redis2.x之後,cacheManager 再也不須要RedisTemplate來建立了 RedisCacheManager cacheManager = RedisCacheManager.builder(jedisConnectionFactory) .build(); cacheManager.initializeCaches(); return cacheManager; } }
須要保存到redis的對象必須implements Serializable。json