创建Client实例

创建Client实例有两种方式:单例和非单例。

单例

如果程序中只需要访问单个集群,那么用单例是比较合适的,这样可以共享各种资源,譬如线程池、连接等。

注意:如果在多个地方调用getSingletonClient()获取单例对象,需要保证传入的configPath是一致的,不然就会抛出异常,这样是为了保证多次调用获取到的是同一个实例。

调用PegasusClientFactory::getSingletonClient()方法获取PegasusClientInterface的单例对象:

  1. // Get the singleton client instance.
  2. // After used, should call PegasusClientFactory.closeSingletonClient() to release resource.
  3. //
  4. // configPath could be:
  5. // - zookeeper path : zk://host1:port1,host2:port2,host3:port3/path/to/config
  6. // - local file path : file:///path/to/config
  7. // - java resource : resource:///path/to/config
  8. public static PegasusClientInterface getSingletonClient(String configPath) throws PException;

使用完毕后,记得close单例以释放资源,譬如:

  1. PegasusClientInterface client = PegasusClientFactory.getSingletonClient(configPath);
  2.  
  3. ... ...
  4.  
  5. PegasusClientFactory.closeSingletonClient();

非单例

如果在程序中需要访问多个集群,就不能用单例了。因此我们提供了创建普通实例的接口,创建时传入一个configPath,不同集群使用不同的configPath。

注意:每个实例都拥有自己独立的资源,互不影响,因此要尽量避免重复创建实例,造成资源浪费,并且使用完后要记得调用close()释放资源。

调用PegasusClientFactory::createClient()方法,获取非单例的client实例:

  1. // Create a client instance.
  2. // After used, should call client.close() to release resource.
  3. public static PegasusClientInterface createClient(String configPath) throws PException;

譬如:

  1. PegasusClientInterface client = PegasusClientFactory.createClient(configPath);
  2.  
  3. ... ...
  4.  
  5. client.close();