将建立的redis连接,作为shared_ptr,定制其析构函数。当析构时重新放入到池中。
核心代码:
新建一个redis连接:
bool RedisConnectPool::new_connect()
{
REDISCLIENTCONTEXT tmp_client_contex(new RedisClientContext(m_host,m_port),bind(&RedisConnectPool::put_connect,this,_1));
if(tmp_client_contex)
{
boost::mutex::scoped_lock locked(m_mutex);
m_redis_client_vec.push_back(tmp_client_contex);
}
else
{
LOG4CPLUS_ERROR(logger,"new connect redis failed");
return false;
}
LOG4CPLUS_ERROR(logger,"new connect redis succ");
return true;
}
定制的析构函数:
void RedisConnectPool::put_connect(RedisClientContext *p)
{
if(!p->m_is_closed)
{
REDISCLIENTCONTEXT redisclientcontext(p,bind(&RedisConnectPool::put_connect,this,_1));
boost::mutex::scoped_lock locked(m_mutex);
m_redis_client_vec.push_back(redisclientcontext);
}
else
{
delete p;
p=NULL;
}
LOG4CPLUS_DEBUG(logger,"now redis contex vector size: "<<m_redis_client_vec.size());
}
获取连接函数:
REDISCLIENTCONTEXT RedisConnectPool::get_connect()
{
REDISCLIENTCONTEXT tmp;
LOG4CPLUS_DEBUG(logger,"before redis contex vector size: "<<m_redis_client_vec.size());
if(m_redis_client_vec.size()==0)
{
if(m_currten_connect<m_max_connect)
{
m_currten_connect++;
new_connect();
}
}
{
boost::mutex::scoped_lock locked(m_mutex);
tmp = m_redis_client_vec.back();
m_redis_client_vec.pop_back();
}
LOG4CPLUS_DEBUG(logger,"now redis contex vector size: "<<m_redis_client_vec.size());
if(!tmp)
{
LOG4CPLUS_ERROR(logger,"we get a null redisconnect");
}
return tmp;
}