Spring Boot 11 : Redis
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
使用 RedisTemplate
/** * Redis 配置 * * @Author YangXuyue * @Date 2018/08/02 21:57 */ @Configuration @EnableCaching @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig extends CachingConfigurerSupport { /** * 设置RedisCacheManager。在配置 CacheManager 的方法中,也可以配置缓存默认的过期时间。 * * @param redisTemplate * @return * @Author YangXuyue * @Date 2018/08/09 07:48 */ @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // 设置缓存过期时间,单位秒 Map<String, Long> expiresMap = new HashMap<>(); expiresMap.put(CacheNames.MASTER, 600L); expiresMap.put(CacheNames.SECOND, 600L); // 设置超时 cacheManager.setExpires(expiresMap); // TODO 没有设置的缓存默认过期时间 //cacheManager.setDefaultExpiration(60 * 60L); return cacheManager; } /** * 使用 StringRedisTemplate * * @param factory * @return * @Author YangXuyue * @Date 2018/08/09 07:48 */ @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } /** * Redis 设置一些全局配置,比如配置主键的生产策略 KeyGenerator,如不配置会默认使用参数名作为主键。 * * @return * @Author YangXuyue * @Date 2018/08/09 07:48 */ @Override @Bean public KeyGenerator keyGenerator() { return new BaseKeyGenerator(); } /** * Redis主键生成策略 * * @Author YangXuyue * @Date 2018/08/09 07:48 */ private class BaseKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { // 目标Object的名称+方法名+Params各个元素名称 StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getSimpleName()); sb.append(".").append(method.getName()); for (Object obj : params) { if (null != obj) { sb.append(obj.toString()); } } return sb.toString(); } } }