Home > Software design >  springboot configuration redis serialization
springboot configuration redis serialization

Time:03-09

Why is the error "Could not autowire. No beans of 'RedisConnectionFactory' type found" reported here?

Serialization doesn't work

I used the new way to inject the object and it didn't solve the problem:

@Configuration
public class RedisConfig {
@Resource
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisTemplate<Object,Object> redisTemplate(){
    RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>();
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    redisTemplate.setConnectionFactory(redisConnectionFactory);

    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

    
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

    
    redisTemplate.setStringSerializer(new StringRedisSerializer());
    return redisTemplate;
}

}

CodePudding user response:

When I was implementing redis server I solved this issue by writing code like this

@Configuration
public class RedisConfiguration {

  @Bean
  @ConditionalOnMissingBean(name = "redisTemplate")
  @Primary
  public <T> RedisTemplate<String, T> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, T> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);

    ObjectMapper om = new ObjectMapper();
    om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    om.registerModule(new JavaTimeModule());

    template.setKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(om));
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer(om));
    return template;
  }
}

This code may be little different from your requirements, but I think if you look closely you can modified according with your needs.

  • Related