自定义RedisTemplate的spring-boot-starter
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-redis</artifactId > </dependency > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-configuration-processor</artifactId > </dependency > <dependency > <groupId > com.fasterxml.jackson.core</groupId > <artifactId > jackson-databind</artifactId > </dependency > </dependencies >
参数配置
1 2 3 4 5 6 7 8 9 10 11 12 13 @ConfigurationProperties(prefix = "spring.redis") public class EasyliaoRedisProperties { private Boolean enable = true ; public Boolean getEnable () { return enable; } public void setEnable (Boolean enable) { this .enable = enable; } }
Redis配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @Configuration @EnableConfigurationProperties(EasyliaoRedisProperties.class) @ConditionalOnProperty(value = "spring.redis.enable", havingValue = "true") public class RedisConfiguration { @Bean("redisTemplate") public RedisTemplate<String, Object> redisTemplate (LettuceConnectionFactory lettuceConnectionFactory) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); RedisSerializer<?> stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
配置spring.factories
在 resource/META-INF/spring.factories
中配置
1 2 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.easyliao.framework.boot.redis.config.RedisConfiguration
使用
引入maven包后, 在 application.properties
中配置 spring.redis.enable=true
后可以自动注入bean, 直接调用
1 2 3 4 5 6 7 8 9 10 11 @Autowired private RedisTemplate<String, Object> redisTemplate;@Test void contextLoads () { User user = new User(); user.setName("admin" ); redisTemplate.opsForValue().set("name" , user); Object name = redisTemplate.opsForValue().get("name" ); System.out.println(name.toString()); }