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


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

1)配置文件

#redis連接配置===================start=========================
# Redis settings
redis.host=192.168.10.102
redis.port=6379
redis.pass=
redis.maxIdle=1
redis.maxActive=9
redis.maxWait=1000
redis.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;

@Controller
public 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 more
Caused 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個

[root@dev2 bin]# ./redis-cli info clients
# Clients
connected_clients:10
client_longest_output_list:0
client_biggest_input_buf:0
blocked_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)重新測試

重新部署,啟動,多次刷新后連接數都沒有出現無法獲取的異常,很正常。

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

 

7)問題解決

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM