Redis配置类和工具类的编写

首先是Redis的简单实用


   org.springframework.boot
   spring-boot-starter-data-redis

配置文件 

spring:
  redis:
    port: 6379
    host: localhost

注入工具

@Autowired
private RedisTemplate redisTemplate;

RedisConfig的编写 

@Configuration
public class RedisConfig {
    //编写自己的RedisTemplate
//自己定义了一个RedisTemplate
//这是一个固定模板,拿去可以直接使用
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate
    redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
//为了我们自己开发方便,一般直接使用
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer
                objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer
                (Object.class);
//json序列化配置
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL,
                JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        objectJackson2JsonRedisSerializer.setObjectMapper(om);
//String的序列化
        StringRedisSerializer stringRedisSerializer = new
                StringRedisSerializer();
//key采用String序列化方式
        template.setKeySerializer(stringRedisSerializer);
//hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
//value的序列化方式采用jackson
        template.setValueSerializer(objectJackson2JsonRedisSerializer);
//hash的value序列化方式采用jackson
        template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
} 
   

你可能感兴趣的:(Redis,RabbitMQ,1024程序员节)