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)
求指教!!!!!!javascript