1,JedisPool的使用
//WHEN_EXHAUSTED_FAIL = 0; 直接抛出异常throw new NoSuchElementException("Pool exhausted");
//WHEN_EXHAUSTED_BLOCK = 1;borrowObject()将会阻塞,直到有可用新的或者空闲的object为止,或者如果配置了maxWait,
//如果请求阻塞超时,将抛出NoSuchElementException.如果maxWait为负数,请求将会无限制的阻
//塞下去,默认配置。
//WHEN_EXHAUSTED_GROW = 2;borrowObject()将会继续创建新的对象,并返回,因此,pool维护的对像数将超出maxActive;
public String set(String key, String value) { Jedis jedis = null; boolean success = true; try { jedis = this.pool.getResource(); return jedis.set(key, value); } catch (JedisException e) { success = false; if(jedis != null){ pool.returnBrokenResource(jedis); } throw e; } finally { if(success && jedis != null){ this.pool.returnResource(jedis); } }
获取Jedis
pool.getResource();
这个可以直接看Pool的getResource方法,
最终还是GenericObjectPool的borrowObject()方法借用对象
@SuppressWarnings("unchecked") public T getResource() { try { return (T) internalPool.borrowObject(); } catch (Exception e) { throw new JedisConnectionException("Could not get a resource from the pool", e); } }
用完归还,调用的是GenericObjectPool的returnObject()方法
pool.returnResource(jedis)
//JedisPool.java public void returnResource(final BinaryJedis resource) { returnResourceObject(resource); } //Pool.java public void returnResourceObject(final Object resource) { try { internalPool.returnObject(resource); } catch (Exception e) { throw new JedisException("Could not return the resource to the pool", e); } }
出错,调用的是GenericObjectPool的invalidateObject()方法
最后在JedisFactory的destroyObject()中调用jedis.quit()请求Server关闭连接
pool.returnBrokenResource(jedis)
//JedisPool.java public void returnBrokenResource(final BinaryJedis resource) { returnBrokenResourceObject(resource); } //Pool.java protected void returnBrokenResourceObject(final Object resource) { try { //失效 internalPool.invalidateObject(resource); } catch (Exception e) { throw new JedisException( "Could not return the resource to the pool", e); } } //GenericObjectPool public void invalidateObject(Object obj) throws Exception { try { if (this._factory != null) this._factory.destroyObject(obj); } finally { synchronized (this) { this._numActive -= 1; allocate(); } } } //JedisFactory public void destroyObject(final Object obj) throws Exception { if (obj instanceof Jedis) { final Jedis jedis = (Jedis) obj; if (jedis.isConnected()) { try { try { jedis.quit(); } catch (Exception e) { } jedis.disconnect(); } catch (Exception e) { } } } }
JedisPool源代码
package redis.clients.jedis; import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool.Config; import redis.clients.util.Pool; public class JedisPool extends Pool { public JedisPool(final Config poolConfig, final String host) { this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisPool(String host, int port) { this(new Config(), host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisPool(final String host) { this(host, Protocol.DEFAULT_PORT); } public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password) { this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE); } public JedisPool(final Config poolConfig, final String host, final int port) { this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisPool(final Config poolConfig, final String host, final int port, final int timeout) { this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE); } public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password, final int database) { super(poolConfig, new JedisFactory(host, port, timeout, password, database)); } public void returnBrokenResource(final BinaryJedis resource) { returnBrokenResourceObject(resource); } public void returnResource(final BinaryJedis resource) { returnResourceObject(resource); } /** * PoolableObjectFactory custom impl. */ private static class JedisFactory extends BasePoolableObjectFactory { private final String host; private final int port; private final int timeout; private final String password; private final int database; public JedisFactory(final String host, final int port, final int timeout, final String password, final int database) { super(); this.host = host; this.port = port; this.timeout = timeout; this.password = password; this.database = database; } public Object makeObject() throws Exception { final Jedis jedis = new Jedis(this.host, this.port, this.timeout); jedis.connect(); if (null != this.password) { jedis.auth(this.password); } if( database != 0 ) { jedis.select(database); } return jedis; } public void destroyObject(final Object obj) throws Exception { if (obj instanceof Jedis) { final Jedis jedis = (Jedis) obj; if (jedis.isConnected()) { try { try { jedis.quit(); } catch (Exception e) { } jedis.disconnect(); } catch (Exception e) { } } } } public boolean validateObject(final Object obj) { if (obj instanceof Jedis) { final Jedis jedis = (Jedis) obj; try { return jedis.isConnected();/* && jedis.ping().equals("PONG");*/ } catch (final Exception e) { return false; } } else { return false; } } } }
其中JedisFactory继承自BasePoolableObjectFactory,只实现了3个方法
makeObject(),连接,new Socket()
destroyObject()--断开连接,
validateObject()--ping
Pool源代码
package redis.clients.util; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; public abstract class Pool { private final GenericObjectPool internalPool; public Pool(final GenericObjectPool.Config poolConfig, PoolableObjectFactory factory) { this.internalPool = new GenericObjectPool(factory, poolConfig); } @SuppressWarnings("unchecked") public T getResource() { try { return (T) internalPool.borrowObject(); } catch (Exception e) { throw new JedisConnectionException( "Could not get a resource from the pool", e); } } public void returnResourceObject(final Object resource) { try { internalPool.returnObject(resource); } catch (Exception e) { throw new JedisException( "Could not return the resource to the pool", e); } } public void returnBrokenResource(final T resource) { returnBrokenResourceObject(resource); } public void returnResource(final T resource) { returnResourceObject(resource); } protected void returnBrokenResourceObject(final Object resource) { try { //失效 internalPool.invalidateObject(resource); } catch (Exception e) { throw new JedisException( "Could not return the resource to the pool", e); } } public void destroy() { try { internalPool.close(); } catch (Exception e) { throw new JedisException("Could not destroy the pool", e); } } }
JedisPoolConfig源代码
public class JedisPoolConfig extends Config { public JedisPoolConfig() { // defaults to make your life with connection pool easier :) setTestWhileIdle(true); setMinEvictableIdleTimeMillis(60000); setTimeBetweenEvictionRunsMillis(30000); setNumTestsPerEvictionRun(-1); } public int getMaxIdle() { return maxIdle; } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } public byte getWhenExhaustedAction() { return whenExhaustedAction; } public void setWhenExhaustedAction(byte whenExhaustedAction) { this.whenExhaustedAction = whenExhaustedAction; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public long getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis( long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public int getNumTestsPerEvictionRun() { return numTestsPerEvictionRun; } public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { this.numTestsPerEvictionRun = numTestsPerEvictionRun; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public long getSoftMinEvictableIdleTimeMillis() { return softMinEvictableIdleTimeMillis; } public void setSoftMinEvictableIdleTimeMillis( long softMinEvictableIdleTimeMillis) { this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis; } }
相关推荐
这个压缩包文件"jedis-master"很可能包含了Jedis的完整源代码,包括测试用例,是学习Jedis的绝佳资源。 1. **Jedis基本使用**: Jedis的使用通常始于创建Jedis实例,通过连接池管理连接。在源码中,你可以看到`...
jedis 2.9jar包括源代码及common-pool 下面是官方地址,不用积分: https://github.com/xetorthio/jedis http://mvnrepository.com/artifact/redis.clients/jedis/2.9.0
java源代码(基于spring-boot)工程介绍:(Jedis存取redis的测试)1、直接连接redis,通过jedis实例直接连接redis,并存入和获取数据2、连接池JedisPool方式连接redis,通过连接池连接redis,可配置最大连接数、...
可以通过`JedisPool`或`LettuceClientResources`实现。 2. 命令执行:大部分Redis操作都可以通过简单的调用Jedis的方法完成,例如`set`、`get`、`lpush`等,但复杂的操作如批量操作和事务处理需要额外的配置。 3. ...
`配置连接池参数,然后`JedisPool pool = new JedisPool(config, "localhost", 6379);`创建连接池,`Jedis jedis = pool.getResource();`获取连接,操作完成后使用`jedis.close();`归还连接。 ### Jedis与Redis其他...
JedisPool pool = new JedisPool(config, "localhost", 6379); try (Jedis jedis = pool.getResource()) { jedis.set("key", "value"); String value = jedis.get("key"); } ``` Jedis还支持事务操作,可以一次...
为了提高性能和资源利用率,Jedis支持连接池管理,可以使用JedisPool类创建和管理连接池。 6. 集群支持: 自Jedis 2.8版本开始,增加了对Redis Cluster的支持,允许在多节点环境中操作数据。 7. 其他特性: ...
对于Java开发者来说,理解如何配置Redis连接池(如JedisPool)以提高性能和资源利用效率也至关重要。连接池允许复用已建立的连接,避免频繁创建和销毁连接带来的开销。同时,了解如何处理异常和关闭资源是保证程序...
3. `jedis-2.9.0-sources.jar`:这个文件包含了Jedis的源代码,开发者可以查看源码来理解Jedis的工作原理,对于学习、调试和贡献代码非常有帮助。 Jedis的主要特性包括: - 连接管理:支持连接池,可配置连接超时...
1. **连接管理**:Jedis提供了连接池功能,通过`JedisPool`和`JedisSentinelPool`实现,可以有效地管理和复用连接,提高性能并避免资源浪费。用户可以根据需求配置连接池的参数,如最大连接数、最大空闲连接数等。 ...
`jedis-jedis-1.5.0-RC1.zip`是一个包含Jedis 1.5.0 Release Candidate 1版本的压缩包,它可能包含了源代码、文档、示例和测试用例等内容,用于开发者在项目中集成或测试Jedis的最新功能。 Jedis的主要特点包括: 1...
Jedis提供了`JedisPool`和`JedisSentinelPool`两种连接池实现,分别用于单一服务器和哨兵模式的Redis集群。 在命令执行方面,Jedis覆盖了Redis的所有基础命令,如字符串操作(`set`、`get`、`append`等)、哈希表...
在本压缩包"jedis-jedis-3.5.0.zip"中,包含的是Jedis库的源代码、文档和其他相关资源。 **Jedis概述** Jedis是一个开源的Java客户端,它实现了Redis的所有命令,并提供了丰富的API供开发者使用。Jedis的设计目标是...
通过`JedisPool`类,开发者可以轻松配置连接池参数,如最大连接数、超时设置等。 2. **基本命令支持**:Jedis支持Redis的所有基础命令,如设置和获取字符串键值(`set`和`get`),执行计数操作(`incr`和`decr`),以及...
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Jedis jedis = jedisPool.getResource(); ...
在这个压缩包"jedis-jedis-2.8.0.tar.gz"中,包含了Jedis库的源代码、文档和其他相关资源,使得开发者可以方便地在项目中集成和使用。 1. **Redis介绍**:Redis是一个开源的、基于键值对的数据存储系统,常被用作...
在"jedis-2.1.0-sources.jar"中,包含了Jedis库的源代码,这对于我们深入理解其内部实现、调试或扩展功能非常有价值。通过查看源码,我们可以了解到以下关键知识点: 1. **连接管理**:Jedis提供了连接池...
3. **jedis-2.9.0-sources.jar**:这个源代码jar包包含了Jedis的完整源代码,对于开发者来说是一个宝贵的学习资源。通过阅读源码,可以深入了解Jedis如何实现与Redis的通信,理解内部工作原理,以及进行自定义扩展或...
3. jedis-2.1.0-sources.jar:这个文件包含了Jedis源代码,对于开发者来说非常有用,可以方便地查看和理解内部实现,进行自定义扩展或者调试。源码可以帮助我们深入学习Jedis的工作原理,比如它是如何执行命令、处理...
在Jedis的源代码中,它可能被用来编写测试用例,确保Jedis的功能正确性和稳定性。 **集成Jedis到项目中** 1. **添加依赖**:将这三个jar包放入项目的类路径中,如果是Maven或Gradle项目,可以在构建配置文件中添加...