Unable to connect to Redis; nested exception is : Unable to

时间:2024-10-06 07:05:03

: Unable to connect to Redis; nested exception is : Unable to connect to localhost/:6379

sprngboot整合redis很简单,之前使用也没有什么问题,基本操作通过redistemplate实现的,配置一下序列化方式就行,一般使用阿里的fastjson。当然也可以使用比较火的fastjson2。
至于yml的配置比较简单,不多赘述
序列化:

  @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(redisConnectionFactory);

        FastJsonRedisSerializer<Object> redisSerializer = new FastJsonRedisSerializer<>(Object.class);

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashValueSerializer(redisSerializer);

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(redisSerializer);

        // 初始化参数
        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

1.其他设置正常的情况下,redis一直连接失败,之前没有设置LettuceConnectionFactory ,springboot项目正常启动,现在一直报错,连接的地址是locahost。而在yml配置的redis的地址为虚拟机地址。正常情况下不应该报错

2.配置redis的LettuceConnectionFactory 要设置连接地址和端口号
3.

    @Bean
    public  LettuceConnectionFactory lettuceConnectionFactory(){

//        new RedisStandaloneConfiguration("192.168.1.6",6379)
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("192.168.1.6");
        redisStandaloneConfiguration.setPort(6379);
        redisStandaloneConfiguration.setDatabase(5);
        return  new LettuceConnectionFactory( redisStandaloneConfiguration);
    }
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.整合springcache的时候用到了LettuceConnectionFactory

    @Bean
    public  CacheManager cacheManager(LettuceConnectionFactory factory){

        // 以锁写入的方式创建对象
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);

        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();

        return new RedisCacheManager(writer, configuration);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

boot data redis 官方文档关于LettuceConnectionFactory配置如下:

The following example shows how to create a new Lettuce connection factory:

@Configuration
class AppConfig {

  @Bean
  public LettuceConnectionFactory redisConnectionFactory() {

    return new LettuceConnectionFactory(new RedisStandaloneConfiguration("server", 6379));
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9