activeConnection = new Vector();
// 记录连接总数
private static int connCount;
// solr连接地址
private String url;
// 初始化连接数
private int initialSize;
// 最大空闲连接数
private int maxIdleSize;
// 最大活动连接数
private int maxActiveSize;
// 等待时间
private int connTimeOut;
public static int getConnCount() {
return connCount;
}
public static void setConnCount(int connCount) {
SolrConnectionPool.connCount = connCount;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getConnTimeOut() {
return connTimeOut;
}
public void setConnTimeOut(int connTimeOut) {
this.connTimeOut = connTimeOut;
}
public int getMaxIdleSize() {
return maxIdleSize;
}
public void setMaxIdleSize(int maxIdleSize) {
this.maxIdleSize = maxIdleSize;
}
public int getMaxActiveSize() {
return maxActiveSize;
}
public void setMaxActiveSize(int maxActiveSize) {
this.maxActiveSize = maxActiveSize;
}
// 初始化
public void init() {
try {
for (int i = 0; i < initialSize; i++) {
HttpSolrClient newConnection = newConnection();
if (newConnection != null) {
// 添加到空闲连接中...
freeConnection.add(newConnection);
}
}
} catch (Exception e) {
e.getStackTrace();
throw new RuntimeException("初始化Solr失败,请检查配置参数!");
}
}
// 创建新的Connection
private HttpSolrClient newConnection() {
HttpSolrClient client = null;
try {
HttpSolrClient.Builder builder = new HttpSolrClient.Builder(url);
client = builder.build();
} catch (Exception e) {
e.getStackTrace();
throw new RuntimeException("创建Solr客户端失败!");
}
connCount++;
return client;
}
public HttpSolrClient getConnection() {
HttpSolrClient connection = null;
try {
if (connCount < maxActiveSize) {
// 还有活动连接可以使用
if (freeConnection.size() > 0) {
connection = freeConnection.remove(0);
} else {
// 创建新的连接
connection = newConnection();
}
if (isAvailable(connection)) {
activeConnection.add(connection);
} else {
connCount--;
connection = getConnection();
}
} else {
synchronized (this) {
// 大于最大活动连接,进行等待,重新获取连接
wait(connTimeOut);
}
connection = getConnection();// 递归调用getConnection方法
}
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
// 判断连接是否可用
public boolean isAvailable(HttpSolrClient connection) {
// 此处没想好怎么判断连接是否可用
if (connection == null) {
return false;
}
return true;
}
// 关闭连接
public void close(HttpSolrClient connection) {
try {
if (isAvailable(connection)) {
// 判断空闲连接集合是否大于最大空闲连接数
if (freeConnection.size() < maxIdleSize) {
freeConnection.add(connection);
} else {
// 空闲连接数已经满了
connection.close();
connCount--;
}
activeConnection.remove(connection);
synchronized (this) {
notifyAll();
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("删除连接出错!");
}
}
}