zoukankan      html  css  js  c++  java
  • RedisTemplate连接不释放、Redis断线不重连问题、Redis连接数高飙升

    使用RedisTemplate操作Redis数据,但遇到网络断线后不会重新连接 毫无头绪  

    一顿捣鼓 最终解决 整理如下 帮助更多的人

    1.起因

    使用RedisTemplate 配置 开启了事务

    enableTransactionSupport=true
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
    		<property name="connectionFactory" ref="jedisConnectionFactory" />
    		<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
    		<property name="keySerializer" >
    			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    		</property>
    		<property name="valueSerializer" >
    			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    		</property>
    		<property name="hashKeySerializer">
    			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    		</property>
    		<property name="hashValueSerializer">
    			<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
    		</property>
    		<!--开启事务  -->
    		<property name="enableTransactionSupport" value="true"></property>
    	</bean >

    或者

    2.发作

    如果遇到网络闪断 而RedisTemplate没有释放连接的话

    网络恢复后 Redis是无法重新连接上的

    3.解决

    方式一:手动判断 关闭连接 例如:

    public Long length(String key) {
            try {
                return redisTemplate.opsForList().size(key);
            } catch (Exception e) {
                logger.error("",e);
            }finally {
                RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
            }
            return null;
        }

    方式二:enableTransactionSupport设置为false(关闭事务)

    4.优化 

    如果一定要开启事务 

    需要在service方法使用 @Transactional 注解 在调用 redisTemplate做好判断

    如果帮到你了 良心三连哦

    最后 我有一本秘籍............ 

  • 相关阅读:
    JSP 隐含对象
    Cookie 和 Session
    Servlet(Server Applet) 详解
    AbstractQueuedSynchronizer 详解
    ThreadLocal 详解
    线程的生命周期
    phpfor函数和foreach函数
    php的while函数
    php的switch函数
    php的if函数
  • 原文地址:https://www.cnblogs.com/weitaming/p/15132589.html
Copyright © 2011-2022 走看看