NebulaGraph Java Client  release-3.6
All Classes Functions Variables
NebulaPool.java
1 /* Copyright (c) 2020 vesoft inc. All rights reserved.
2  *
3  * This source code is licensed under Apache 2.0 License.
4  */
5 
6 package com.vesoft.nebula.client.graph.net;
7 
8 import com.vesoft.nebula.client.graph.NebulaPoolConfig;
9 import com.vesoft.nebula.client.graph.data.HostAddress;
10 import com.vesoft.nebula.client.graph.exception.AuthFailedException;
11 import com.vesoft.nebula.client.graph.exception.ClientServerIncompatibleException;
12 import com.vesoft.nebula.client.graph.exception.IOErrorException;
13 import com.vesoft.nebula.client.graph.exception.InvalidConfigException;
14 import com.vesoft.nebula.client.graph.exception.NotValidConnectionException;
15 import java.io.Serializable;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.concurrent.atomic.AtomicBoolean;
21 import org.apache.commons.pool2.impl.AbandonedConfig;
22 import org.apache.commons.pool2.impl.BaseObjectPoolConfig;
23 import org.apache.commons.pool2.impl.GenericObjectPool;
24 import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 
28 public class NebulaPool implements Serializable {
29 
30  private static final long serialVersionUID = 6226487268001127885L;
31 
32  private GenericObjectPool<SyncConnection> objectPool = null;
33  private LoadBalancer loadBalancer;
34  private final Logger log = LoggerFactory.getLogger(this.getClass());
35  // the wait time to get idle connection, unit ms
36  private int waitTime = 0;
37  private AtomicBoolean hasInit = new AtomicBoolean(false);
38  private AtomicBoolean isClosed = new AtomicBoolean(false);
39 
40  private void checkConfig(NebulaPoolConfig config) {
41  if (config.getIdleTime() < 0) {
42  throw new InvalidConfigException(
43  "Config idleTime:" + config.getIdleTime() + " is illegal");
44  }
45 
46  if (config.getMaxConnSize() <= 0) {
47  throw new InvalidConfigException(
48  "Config maxConnSize:" + config.getMaxConnSize() + " is illegal");
49  }
50 
51  if (config.getMinConnSize() < 0 || config.getMinConnSize() > config.getMaxConnSize()) {
52  throw new InvalidConfigException(
53  "Config minConnSize:" + config.getMinConnSize() + " is illegal");
54  }
55 
56  if (config.getTimeout() < 0) {
57  throw new InvalidConfigException(
58  "Config timeout:" + config.getTimeout() + " is illegal");
59  }
60 
61  if (config.getWaitTime() < 0) {
62  throw new InvalidConfigException(
63  "Config waitTime:" + config.getWaitTime() + " is illegal");
64  }
65 
66  if (config.getMinClusterHealthRate() < 0) {
67  throw new InvalidConfigException(
68  "Config minClusterHealthRate:" + config.getMinClusterHealthRate()
69  + " is illegal");
70  }
71  }
72 
81  public boolean init(List<HostAddress> addresses, NebulaPoolConfig config)
82  throws UnknownHostException, InvalidConfigException {
83  checkInit();
84  hasInit.set(true);
85  checkConfig(config);
86  this.waitTime = config.getWaitTime();
87  this.loadBalancer = config.isEnableSsl()
88  ? new RoundRobinLoadBalancer(addresses, config.getTimeout(), config.getSslParam(),
89  config.getMinClusterHealthRate(), config.isUseHttp2(), config.getCustomHeaders())
90  : new RoundRobinLoadBalancer(addresses, config.getTimeout(),
91  config.getMinClusterHealthRate(),config.isUseHttp2(), config.getCustomHeaders());
92  ConnObjectPool objectPool = new ConnObjectPool(this.loadBalancer, config);
93  this.objectPool = new GenericObjectPool<>(objectPool);
94  GenericObjectPoolConfig objConfig = new GenericObjectPoolConfig();
95  objConfig.setMinIdle(config.getMinConnSize());
96  objConfig.setMaxIdle(config.getMaxConnSize());
97  objConfig.setMaxTotal(config.getMaxConnSize());
98  objConfig.setTestOnBorrow(true);
99  objConfig.setTestOnReturn(true);
100  objConfig.setTestOnCreate(true);
101  objConfig.setTestWhileIdle(true);
102  objConfig.setTimeBetweenEvictionRunsMillis(config.getIntervalIdle() <= 0
103  ? BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS
104  : config.getIntervalIdle());
105  objConfig.setSoftMinEvictableIdleTimeMillis(config.getIdleTime() <= 0
106  ? BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS
107  : config.getIdleTime());
108  this.objectPool.setConfig(objConfig);
109 
110  AbandonedConfig abandonedConfig = new AbandonedConfig();
111  abandonedConfig.setRemoveAbandonedOnBorrow(true);
112  this.objectPool.setAbandonedConfig(abandonedConfig);
113  return objectPool.init();
114  }
115 
119  public void close() {
120  if (isClosed.get()) {
121  return;
122  }
123  isClosed.set(true);
124  this.loadBalancer.close();
125  this.objectPool.close();
126  }
127 
138  public Session getSession(String userName, String password, boolean reconnect)
141  checkNoInitAndClosed();
142  SyncConnection connection = null;
143  try {
144  connection = getConnection();
145  AuthResult authResult = connection.authenticate(userName, password);
146  return new Session(connection, authResult, this, reconnect);
147  } catch (Exception e) {
148  // if get the connection succeeded, but authenticate failed,
149  // needs to return connection to pool
150  if (connection != null) {
151  setInvalidateConnection(connection);
152  }
153  throw e;
154  }
155  }
156 
161  public int getActiveConnNum() {
162  checkNoInitAndClosed();
163  return objectPool.getNumActive();
164  }
165 
170  public int getIdleConnNum() {
171  checkNoInitAndClosed();
172  return objectPool.getNumIdle();
173  }
174 
179  public int getWaitersNum() {
180  checkNoInitAndClosed();
181  return objectPool.getNumWaiters();
182  }
183 
188  protected void updateServerStatus() {
189  checkNoInitAndClosed();
190  if (objectPool.getFactory() instanceof ConnObjectPool) {
191  ((ConnObjectPool) objectPool.getFactory()).updateServerStatus();
192  }
193  }
194 
199  protected void setInvalidateConnection(SyncConnection connection) {
200  checkNoInitAndClosed();
201  try {
202  objectPool.invalidateObject(connection);
203  } catch (Exception e) {
204  log.error("Set invalidate object failed");
205  }
206  }
207 
212  protected void returnConnection(SyncConnection connection) {
213  checkNoInitAndClosed();
214  objectPool.returnObject(connection);
215  }
216 
217  protected SyncConnection getConnection() throws NotValidConnectionException {
218  checkNoInitAndClosed();
219  try {
220  return objectPool.borrowObject(waitTime);
221  } catch (Exception e) {
222  throw new NotValidConnectionException(e.getMessage());
223  }
224  }
225 
226  private void checkNoInit() throws RuntimeException {
227  if (!hasInit.get()) {
228  throw new RuntimeException(
229  "The pool has not been initialized, please initialize it first.");
230  }
231  }
232 
233  private void checkInit() throws RuntimeException {
234  if (hasInit.get()) {
235  throw new RuntimeException(
236  "The pool has already been initialized. "
237  + "Please do not initialize the pool repeatedly.");
238  }
239  }
240 
241  private void checkNoInitAndClosed() throws RuntimeException {
242  checkNoInit();
243  checkClosed();
244  }
245 
246  private void checkClosed() throws RuntimeException {
247  if (isClosed.get()) {
248  throw new RuntimeException("The pool has closed. Couldn't use again.");
249  }
250  }
251 }
int getActiveConnNum()
Get the number of connections was used by users.
int getIdleConnNum()
Get the number of free connections in the pool.
void updateServerStatus()
Update the services' status when the connection is broken, it is called by Session and NebulaPool.
void setInvalidateConnection(SyncConnection connection)
Set the connection is invalidate, and the object pool will destroy it.
Session getSession(String userName, String password, boolean reconnect)
get a session from the NebulaPool
int getWaitersNum()
Get the number of waits in a waiting get connection.
void close()
close the pool, all connections will be closed
boolean init(List< HostAddress > addresses, NebulaPoolConfig config)
Definition: NebulaPool.java:81
void returnConnection(SyncConnection connection)
Return the connection to object pool.
The Session is an object that operates with nebula-graph.
Definition: Session.java:53