0

我正在实现一个连接池(JDBC 连接和 SMPP 连接)。我知道那里有几个经过良好测试的连接池。但我只想自己实现。我在多线程环境中使用它。这更多是我个人的兴趣。我的实现是这样的。我创建一个 ConcurrentLinkedQueue 并将连接推送到队列。每次线程请求连接时,连接都会从队列中弹出。一旦工作完成,线程将连接推回队列。我的连接轮询实现类如下图所示。

import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.log4j.Logger;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;


public class SMPPConnectionPool {
    static ConcurrentLinkedQueue<SMPPSession> connectionPool = null;
    static Logger LOG = null;

    static 
    {
        LOG = LogManager.getLogger(SMPPConnectionPool.class);
        connectionPool= new ConcurrentLinkedQueue<SMPPSession>();
    }

    /* This method returns session from queue .If no sessions exist in the queue,then a new session will be created and returned.
     * This method use QueryGparams APi to read conenction related data from gparams
     * */
    public static SMPPSession getConenction()
    {
        SMPPSession session=connectionPool.poll();
        if(session!=null)
        {
            System.out.println("Thread "+Thread.currentThread().getName() +" got "+session.getSessionId());
            LOG.info("Thread "+Thread.currentThread().getName() +" got "+session.getSessionId());
            return session;
        }
        else
        {
            SMPPSession smppSession = new SMPPSession();
            try {
                String host = QueryGparams.getGparamAsString(NotificationConstants.SMSC_HOST);
                int port = QueryGparams.getGparamAsInteger(NotificationConstants.SMSC_PORT);
                String systemId = QueryGparams.getGparamAsString(NotificationConstants.SMSC_SYSTEM_ID);
                String password = QueryGparams.getGparamAsString(NotificationConstants.SMSC_PASSWORD);
                if(host == null || systemId == null || password == null || port == 0)
                {
                    String errorMessage = "Following parameters are null \n";
                    if(host == null) {
                        errorMessage = errorMessage + "host is null";
                    }
                    if(systemId == null) {
                        errorMessage = errorMessage + "systemId is null";
                    }
                    if(password == null) {
                        errorMessage = errorMessage + "password is null";
                    }
                    if(port == 0) { //TODO Need to change this if QueryGParams API will not return zero when port number is not specified 
                        errorMessage = errorMessage + "port is null";
                    }
                    throw new Exception(errorMessage);
                }
                smppSession
                .connectAndBind(host,port, new BindParameter(
                        BindType.BIND_TRX, systemId,
                        password, "",
                        TypeOfNumber.UNKNOWN,
                        NumberingPlanIndicator.UNKNOWN, null));
                LOG.info("Session has been created.Session id is "+smppSession.getSessionId());
            } catch (Exception e) {
                LOG.error(CommonUtilities.getExceptionString(e));
            }
            System.out.println("Thread "+Thread.currentThread().getName() +" got "+smppSession.getSessionId());
            LOG.info("Thread "+Thread.currentThread().getName() +" got "+smppSession.getSessionId());
            return smppSession;
        }
    }



    //This method pushes conenction back to queue ,to make it available for other threads. 
    public static void pushConenction(SMPPSession smppSession)
    {
        boolean isInserted=connectionPool.offer(smppSession);
        if(isInserted)
        {
            LOG.info("Pushed the conenction back to queue");
            System.out.println("Pushed the conenction back to queue");
        }
        else
        {
            LOG.info("Failed to push the session back to queue");
            System.out.println("Failed to push the session back to queue");
        }
    }
    public static void closeSessions()
    {
        while(connectionPool!=null && connectionPool.size()>0)
        {
            SMPPSession session=connectionPool.poll();
            session.unbindAndClose();
            LOG.info("Closed the session");
        }
    }

}

我只是想知道这个实现的问题。请建议。我想对 JDBC 连接池实现做同样的事情

4

2 回答 2

0

1) boolean isInserted=connectionPool.offer(smppSession); 并且随后的分析没有意义,因为 ConcurrentLinkedQueue 是无界的,并且它的 offer() 总是返回 true。见 API

2)如果达到最大活动阈值,我将使用 BlockingQueue 并使线程等待活动线程返回连接池

3)我会以这种方式初始化静态字段

static ConcurrentLinkedQueue<SMPPSession> connectionPool = new ConcurrentLinkedQueue<SMPPSession>();
static Logger LOG = LogManager.getLogger(SMPPConnectionPool.class);

4)为了避免不必要的字符串连接,你可以使用这个成语

if (LOG.isInfoEnabled()) {
   LOG.info("Thread "+Thread.currentThread().getName() +" got "+smppSession.getSessionId());
}

5)这似乎很可疑

} catch (Exception e) {
    LOG.error(CommonUtilities.getExceptionString(e));
}
System.out.println("Thread "+Thread.currentThread().getName() +" got "+smppSession.getSessionId());

您捕获异常并继续,好像一切正​​常

于 2013-09-21T06:40:50.230 回答
0

我在实现中看到的一些问题如下:

  1. 没有为 connectAndBind 配置超时。在网络分区或数据包丢失的情况下,getConnection 调用很可能会被卡住。

  2. 在网络中断的情况下,数据源和客户端之间的 TCP 连接可能会中断。因此,池持有的连接将是陈旧的。似乎不存在可以“刷新”连接的机制。许多连接池框架提供 testConnections 以在后台或在检查连接之前执行(这当然会增加整个 getConnection 调用的延迟)以应对此问题。

于 2013-09-21T06:44:25.823 回答