本文使用的是spring-data-redisredis
首先说下redis最简单得使用,除去配置。spring
须要在你要使用得缓存得地方,例如mybatis在mapper.xml中加入:数据库
<cache eviction="LRU" type="cn.jbit.cache.RedisCache"/>缓存
因为是第一次使用redis,再调试代码得时候报错:Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool] with root causemybatis
没法得到redis的连接。app
方法1.从新配置了redis链接池得参数:须要按照本身缓存的数量而设置最大连接数。spa
#最大空闲数,数据库链接的最大空闲时间。超过空闲数量,数据库链接将被标记为不可用,而后被释放。设为0表示无限制 redis.maxIdle=50 #最大链接数:可以同时创建的“最大连接个数”#jedis的最大活跃链接数设为0表示无限制,这个属性就是高版本的maxTotal redis.maxActive=50 #最大等待时间:单位ms #jedis池没有链接对象返回时,等待可用链接的最大时间,单位毫秒,默认值为-1,表示永不超时。 #若是超过等待时间,则直接抛出JedisConnectionException redis.maxWait=1000 ##############################问题注解############################### 注解:运行报错:Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool] with root cause maxActive是最大激活链接数,这里取值为50,表示同时最多有50个数据连 接。maxIdle是最大的空闲链接数,这里取值为50, 表示即便没有数据库链接时依然能够保持20空闲的链接,而不被清除,随时处于待命状态。MaxWait是最大等待秒钟数,这里取值-1, 表示无限等待,直到超时为止,通常取值3000,表示3秒后超时。 而本身开始的设置是:redis.maxIdle=10 redis.maxActive=50 #########################################################################
若是问题继续存在
方法2.问题仍是没解决,屡次调试,发现连接资源没释放有关系,固然个人代码中是作了资源释放的。
先看poolConfig
<!-- redis数据源 --> <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>
redis.properties文件配置
#最大连接数 redis.maxTotal=100 #最大空闲数,数据库链接的最大空闲时间。超过空闲数量,数据库链接将被标记为不可用,而后被释放。设为0表示无限制 redis.maxIdle=20 ##jedis的最大活跃链接数设为0表示无限制 redis.maxActive=100 #最大等待时间:单位ms #jedis池没有链接对象返回时,等待可用链接的最大时间,单位毫秒,默认值为-1,表示永不超时。 #若是超过等待时间,则直接抛出JedisConnectionException redis.maxWait=1000 #使用链接时,检测链接是否成功 redis.testOnBorrow=true
redis文件
public void clear() { JedisConnection connection = null; try { connection = jedisConnectionFactory.getConnection(); connection.flushDb(); connection.flushAll(); System.out.println("clear=redis======>"); } catch (JedisConnectionException e) { connection.close();//释放连接 e.printStackTrace(); } finally { if (connection != null) { connection.close();//释放链接 } } }
问题的主要缘由是使用链接池的连接后没有释放资源,固然开始个人代码就释放了使用的连接资源,可是仍是会出现连接资源拿不到的状况。
多是由于异常没有释放连接资源,我这个getConnection()是使用的第三方静态注入依赖于ehcache,只须要在须要缓存的dao或者mapper
加入注解,便可缓存并同步刷新最新数据。不须要在业务层手动的set,update,remove数据。
若是是getResource()这种方式获取的redis连接,用returnToPool(jedis)或jedis.close()是能够解决问题的;
最让咱们忽略的缘由就是你的redis是山寨版集成的,重新手博客上直接copy被坑的不要不要的。要么用spring boot集成的redis要么集成原生的。
具体状况酌情处理