redis在應用中使用串連不釋放問題解決

來源:互聯網
上載者:User

標籤:

今天測試,發現redis使用的時候,調用的連結一直不釋放。後查閱蠻多資料,才發現一個配置導致的。並不是他們說的服務沒有啟動導致的。

1)設定檔

#redis串連配置===================start=========================# Redis settingsredis.host=192.168.10.102redis.port=6379redis.pass=redis.maxIdle=1redis.maxActive=9redis.maxWait=1000redis.testOnBorrow=true#redis串連配置===================end=========================

 

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"      xmlns:context="http://www.springframework.org/schema/context"      xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"      xmlns:aop="http://www.springframework.org/schema/aop"      xsi:schemaLocation="              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">      <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">        <property name="maxIdle" value="${redis.maxIdle}" />        <property name="maxTotal" value="${redis.maxActive}" />        <property name="maxWaitMillis" value="${redis.maxWait}" />        <property name="testOnBorrow" value="${redis.testOnBorrow}" />    </bean>    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <property name="poolConfig" ref="poolConfig" />          <property name="port" value="${redis.port}" />          <property name="hostName" value="${redis.host}" />          <property name="password" value="${redis.pass}" />         </bean>    <bean id="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>        <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>        <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory" />        <property name="keySerializer" ref="stringSerializer" />        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>        <property name="enableTransactionSupport" value="true"/>    </bean>    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory" />        <property name="keySerializer" ref="stringSerializer" />        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>    </bean></beans>

 

2)測試例子

寫了一個springmvc的controller類,然後調用線程使用串連,出現問題。

DemoMvcController.java

package com.iafclub.demo.web.controller;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.iafclub.baseTools.util.MyDateUtil;@Controllerpublic class DemoMvcController {        @Autowired    private StringRedisTemplate stringRedisTemplate;    /**     * 跳轉方式3     * */    @RequestMapping("/testRedis.do")    public void testRedis(Model model, HttpServletRequest request){        System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");        for(int i=0;i<5;i++){            Thread thread = new RedisThread(stringRedisTemplate);            thread.setName("線程:" + i);            thread.start();        }        model.addAttribute("status", "完成"+MyDateUtil.getCurrentDateTimeStr());        System.out.println("完成");        System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");        }}

RedisThread.java線程類

package com.iafclub.demo.web.controller;import org.junit.runner.RunWith;import org.springframework.data.redis.core.BoundValueOperations;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.iafclub.baseTools.util.MyDateUtil;@RunWith(SpringJUnit4ClassRunner.class)public class RedisThread extends Thread {    private StringRedisTemplate redisTemplate;        private String REVERSE_KEY = "batchJob:task_";    public RedisThread(StringRedisTemplate redisTemplate){        this.redisTemplate = redisTemplate;    }        @Override    public void run() {        // 其實這裡使用了多次,但是使用的也都是一個連結        for(int i=0;i<50;i++){            String value = Thread.currentThread().getName() + "{user:user"+MyDateUtil.getCurrentDateTimeStr()+";name:chenweixian"+System.currentTimeMillis()+"}";            redisTemplate.opsForValue().set(REVERSE_KEY+System.currentTimeMillis(), value);            redisTemplate.getConnectionFactory().getConnection().close();//            BoundValueOperations<String, String> opt = redisTemplate.boundValueOps(REVERSE_KEY+System.currentTimeMillis());//            opt.set(value);//            System.out.println(opt.get());        }        System.out.println("完成");    }    }

啟動應用,訪問連結:http://chenweixian-pc:8480/demo-system/testRedis.do,多重新整理幾次

出現問題異常:Cannot get Jedis connection

Exception in thread "線程:3" org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:162)    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:251)    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:58)    at com.iafclub.demo.web.controller.RedisThread.run(RedisThread.java:26)Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool    at redis.clients.util.Pool.getResource(Pool.java:50)    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:88)    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:12)    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:155)    ... 3 moreCaused by: java.util.NoSuchElementException: Timeout waiting for idle object    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:442)    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:360)    at redis.clients.util.Pool.getResource(Pool.java:48)    ... 6 more

3)查看連結數

通過用戶端工具到伺服器去查詢當前串連數:當前10個

[[email protected] bin]# ./redis-cli info clients# Clientsconnected_clients:10client_longest_output_list:0client_biggest_input_buf:0blocked_clients:0

 

4)分析問題 

 

因為我們設定最初的串連數最大是9個,加上我自己通過用戶端訪問串連數10個,理論上應該釋放才對,這裡沒有釋放,是有問題的。因為這個連結應該是與資料庫連結一樣,會釋放,才能長久。。。

間隔很久訪問,依舊是10個。沒有釋放。一旦有httprequest請求發出來,錯誤依舊是:沒有取到連結。

Exception in thread "線程:3" org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

 

5)修改配置

經過反覆尋找屬性,最終在設定檔中發現一個配置,是交易處理的,網上查詢得知,如果啟動了redis中的交易管理,必須使用mul和execute執行後才會生效。而我們這裡沒有使用這個事務。so去掉這個配置。

    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory" />        <property name="keySerializer" ref="stringSerializer" />        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>        <property name="enableTransactionSupport" value="true"/>    </bean>

 

6)重新測試

重新部署,啟動,多次重新整理後串連數都沒有出現無法擷取的異常,很正常。

# Clientsconnected_clients:1client_longest_output_list:0client_biggest_input_buf:0blocked_clients:0

 

7)問題解決

總結:這個配置項,需要注意。。

redis在應用中使用串連不釋放問題解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.