从jedisConnectionFactory获取Jedis实例报错

本文介绍了一个基于Redis实现的抢红包功能,并发场景下出现的异常及其原因分析。通过Lua脚本保证了抢红包过程的原子性,但在高并发情况下遇到了资源池等待超时的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1 // redisTemplate配置
  2 @Bean(name="redisTemplate")
  3     public RedisTemplate initRedisTemplate() {
  4         JedisPoolConfig poolConfig = new JedisPoolConfig();
  5         //最大空闲数
  6         poolConfig.setMaxIdle(50);
  7         //最大连接数
  8         poolConfig.setMaxTotal(1000);
  9         //最大等待毫秒数
 10         poolConfig.setMaxWaitMillis(20000);
 11 
 12         poolConfig.setTestOnBorrow(true);
 13 
 14         //创建Jedis连接工厂
 15         JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
 16         connectionFactory.setHostName("localhost");
 17         connectionFactory.setPort(6379);
 18         System.out.println("conn是否为空:"+(connectionFactory == null));
 19         //调用后初始化方法,没有它将抛出异常
 20         connectionFactory.afterPropertiesSet();
 21         //定义Redis序列化器
 22         RedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
 23         RedisSerializer stringRedisSerializer = new StringRedisSerializer();
 24         //定义RedisTemlpate,并设置连接工厂
 25         RedisTemplate redisTemplate = new RedisTemplate<>();
 26         redisTemplate.setConnectionFactory(connectionFactory);
 27         //设置序列化器
 28         redisTemplate.setDefaultSerializer(stringRedisSerializer);
 29         redisTemplate.setKeySerializer(stringRedisSerializer);
 30         redisTemplate.setValueSerializer(stringRedisSerializer);
 31         redisTemplate.setHashKeySerializer(stringRedisSerializer);
 32         redisTemplate.setHashValueSerializer(stringRedisSerializer);
 33 
 34         return redisTemplate;
 35     }
 36 -------------------------分割线------------------------------------
 37     //Service中使用的代码
 38     /**
 39      * 使用redis进行操作
 40      * */
 41     @ResponseBody
 42     @RequestMapping("/grapRedPacketByRedis.do")
 43     public Map<String, Object> grapRedPacketByRedis(Integer redPacketId, Integer userId){
 44         //抢红包
 45         int result= userRedPacketService.grapRedPacketByRedis(redPacketId, userId);
 46         Map<String,Object> retMap = new HashMap<>();
 47         boolean flag = result>0;
 48         retMap.put("success", flag);
 49         retMap.put("message", flag?"抢红包成功":"抢红包失败");
 50 
 51         return retMap;
 52     }
 53 -------------------------分割线------------------------------------
 54     //在Service中注入
 55     @Autowired
 56     private RedisTemplate redisTemplate = null;
 57     ....
 58     //Lua脚本
 59     String script = "local listKey = 'red_pakcet_list_' ..KEYS[1] \n"
 60                     +"local redPacket = 'red_packet_' ..KEYS[1] \n"
 61                     +"local stock = tonumber(redis.call('hget',redPacket, 'stock')) \n"
 62                     +"if stock <=0 then return 0 end \n"
 63                     +"stock = stock-1 \n"
 64                     +"redis.call('hset',redPacket,'stock',tostring(stock)) \n"
 65                     +"redis.call('rpush',listKey, ARGV[1]) \n"
 66                     +"if stock ==0 then return 2 end \n"
 67                     +"return 1 \n";
 68     //在缓存Lua脚本后,使用该变量保存Redis返回的32位的SHA1编码, 使用它去执行缓存的Lua脚本
 69     String sha1 = null;
 70 
 71     //使用的方法
 72     @Override
 73     public Integer grapRedPacketByRedis(Integer redPacketId, Integer userId) {
 74         //当前抢红包用户和日期信息
 75         String args = userId+"-"+System.currentTimeMillis();
 76         Integer result = null;
 77         //获取底层Redis操作对象
 78         Jedis jedis = (Jedis) redisTemplate .getConnectionFactory().getConnection().getNativeConnection();
 79         try {
 80             //如果脚本没有加载过,那么进行加载,这样就会返回一个sha1编码
 81             if(sha1 == null) {
 82                 sha1 = jedis.scriptLoad(script);
 83             }
 84             //执行脚本,返回结果
 85             Object res = jedis.evalsha(sha1,1,redPacketId+"",args);
 86             result = Integer.parseInt(res+"");
 87             //返回2 时为最后一个红包,此时将抢红包信息通过异步保存到数据库
 88             if(result == 2) {
 89                 //获取单个小金额红包
 90                 String unitAmountStr = jedis.hget("red_packet_"+redPacketId, "unit_amount");
 91                 //触发保存数据库操作
 92                 Double unitAmount = Double.parseDouble(unitAmountStr);
 93                 System.out.println("thread_name="+Thread.currentThread().getName());
 94                 redisRedPacketService.saveUserRedPacketByRedis(redPacketId, unitAmount);
 95             }
 96         } finally {
 97             //确保jedis关闭
 98             if(jedis != null && !jedis.isConnected()) {
 99                 jedis.close();
100             }
101         }
102         return result;
103     }
104 -------------------------分割线------------------------------------
105     // 前端js请求
106     <script type="text/javascript">
107     $().ready(function(){
108         //模拟30000个异步请求,进行并发
109         var max = 30000;
110         for (var i = 1; i <= max; i++) {
111             // jQuery的post请求, 这里是异步请求
112             $.post({
113                 //请求抢id为1的红包
114                 url:"./userRedPacket/grapRedPacketByRedis.do?redPacketId=3&userId="+i,
115                 success:function(result){
116                 }               
117             });
118         }
119     });
120 </script>

后台异常:
//获取底层Redis操作对象
Jedis jedis = (Jedis) redisTemplate .getConnectionFactory().getConnection().getNativeConnection();
这句异常!!
 
三月 01, 2018 3:10:17 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [dispatcher] in context with path [/RedPacket] threw exception [Request processing failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool] with root cause
java.util.NoSuchElementException: Timeout waiting for idle object
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:449)
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
    at redis.clients.util.Pool.getResource(Pool.java:49)
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:226)
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:16)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:194)
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:348)
    at com.avc.rp.service.impl.UserRedPacketServiceImpl.grapRedPacketByRedis(UserRedPacketServiceImpl.java:151)
    at sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy33.grapRedPacketByRedis(Unknown Source)
    at com.avc.rp.controller.UserRedPacketController.grapRedPacketByRedis(UserRedPacketController.java:40)
    at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:500)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

求指教!!!!!!


 

转载于:https://www.cnblogs.com/amvilcresx/p/8488768.html

### jedis 连接报错的原因与解决方案 在使用 Jedis 连接 Redis 时,常见的报错原因包括配置问题、网络限制、以及 Redis 服务端设置等。以下是常见原因及对应的解决方案: #### 1. **密码配置问题** 如果 Redis 未设置密码,但在 JedisPool 的构造方法中传入了空字符串 `""`,则可能导致连接失败。正确的做法是将密码参数设置为 `null`,或者使用不包含密码参数的构造方法。例如: ```java if (StringUtil.isBlank(password)) { password = null; } JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); ``` 此外,也可以使用仅需 URI 参数的构造方法,例如 `JedisPool(final URI uri)`,避免密码相关的配置问题[^1]。 #### 2. **绑定地址限制** 默认情况下,Redis 服务器的 `bind` 配置为 `127.0.0.1`,这意味着只有本机可以连接,其他机器无法访问。如果需要远程连接,必须修改 `redis.conf` 文件中的 `bind` 地址为服务器的实际 IP 地址。可以使用 `ifconfig` 命令查看虚拟机或服务器的 IP 地址,并将其配置到 Redis 的配置文件中。 ```bash bind 192.168.1.100 ``` 修改完成后,重启 Redis 服务以使新配置生效[^2]。 #### 3. **保护模式限制** Redis 从 3.2 版本开始引入了保护模式(Protected Mode),它会限制客户端的访问,尤其是在未设置密码的情况下。如果需要允许远程连接,可以通过以下命令禁用保护模式: ```bash CONFIG SET protected-mode no ``` 为了使更改永久生效,可以使用以下命令写入配置文件: ```bash CONFIG REWRITE ``` 需要注意的是,禁用保护模式后,应确保 Redis 不暴露在公网中,以免引发安全问题[^3]。 #### 4. **防火墙限制** 在某些操作系统(如 CentOS 7)中,默认启用了 `firewalld` 防火墙,可能会阻止外部访问 Redis 端口(默认为 6379)。如果遇到连接超时的问题,可以尝试关闭防火墙: ```bash # 关闭防火墙 systemctl stop firewalld.service # 禁用防火墙开机启动 systemctl disable firewalld.service ``` 或者,可以配置防火墙规则,允许特定端口通过: ```bash firewall-cmd --permanent --add-port=6379/tcp firewall-cmd --reload ``` 这样可以在不关闭防火墙的前提下,允许 Jedis 连接 Redis 服务器[^4]。 #### 5. **连接超时** Jedis 连接超时通常是由于网络延迟或服务器响应慢导致的。可以通过设置合理的超时时间来避免此类问题。例如,在创建 JedisPool 时,可以指定连接超时时间: ```java JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); ``` 其中,`timeout` 参数表示连接超时时间(单位为毫秒),可以根据实际网络状况进行调整。 #### 6. **资源池配置不合理** JedisPool 的配置参数不合理也可能导致连接问题。常见的配置参数包括: - `setMaxIdle(int maxIdle)`:设置最大空闲连接数。 - `setMaxWaitMillis(long maxWait)`:设置获取连接的最大等待时间。 - `setMaxTotal(int maxTotal)`:设置最大连接数。 - `setMinIdle(int minIdle)`:设置最小空闲连接数。 合理配置这些参数可以提升连接效率,避免资源耗尽或连接等待时间过长。 #### 7. **Jedis 版本兼容性问题** 不同版本的 Jedis 对 Redis 的支持可能存在差异。如果遇到连接问题,可以尝试升级或降级 Jedis 版本,确保其与 Redis 服务器的版本兼容。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值