栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot多线程访问Redis报错超时异常解决

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot多线程访问Redis报错超时异常解决

   @Test
   public void testRedis() {
        // 多线程访问相同key
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                // 不存在,则set
                stringRedisTemplate.opsForValue().setIfAbsent("key:1", "1");
            }, i+"").start();
        }
    }

报错如下:

org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to localhost:6379

redis并发多线程连接报超时异常,不能使用lettuce连接池,改用jedis连接池,修改如下:

        
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
            
                
                    lettuce-core
                    io.lettuce
                
            
        
        
        
            org.apache.commons
            commons-pool2
        
        
        
            redis.clients
            jedis
        
spring  
  #redis相关配置
  redis:
    # 指定库,默认0库,全部16个库
    database: 3
    # 配置redis的主机地址,需要修改成自己的
    host: localhost
    port: 6379
    password:
    timeout: 5000
    jedis:
      pool:
        # 连接池中的最大空闲连接,默认值也是8。
        max-idle: 500
        # 连接池中的最小空闲连接,默认值也是0。
        min-idle: 50
        # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)
        max-active: 1000
        # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
        max-wait: 2000
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfig {

    
    @Bean
    public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        return redisTemplate;
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/336690.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号