Interface ClientBuilder

All Superinterfaces:
Cloneable, Serializable

@Public @Stable public interface ClientBuilder extends Serializable, Cloneable
Builder interface that is used to configure and construct a PulsarClient instance.
Since:
2.0.0
  • Method Details

    • build

      Construct the final PulsarClient instance.
      Returns:
      the new PulsarClient instance
      Throws:
      PulsarClientException
    • loadConf

      ClientBuilder loadConf(Map<String,Object> config)
      Load the configuration from provided config map.

      Example:

       
       Map<String, Object> config = new HashMap<>();
       config.put("serviceUrl", "pulsar://localhost:6650");
       config.put("numIoThreads", 20);
      
       ClientBuilder builder = ...;
       builder = builder.loadConf(config);
      
       PulsarClient client = builder.build();
       
       
      Parameters:
      config - configuration to load
      Returns:
      the client builder instance
    • clone

      ClientBuilder clone()
      Create a copy of the current client builder.

      Cloning the builder can be used to share an incomplete configuration and specialize it multiple times. For example:

      
       ClientBuilder builder = PulsarClient.builder()
                     .ioThreads(8)
                     .listenerThreads(4);
      
       PulsarClient client1 = builder.clone()
                        .serviceUrl("pulsar://localhost:6650").build();
       PulsarClient client2 = builder.clone()
                        .serviceUrl("pulsar://other-host:6650").build();
       
      Returns:
      a clone of the client builder instance
    • serviceUrl

      ClientBuilder serviceUrl(String serviceUrl)
      Configure the service URL for the Pulsar service.

      This parameter is required.

      Examples:

      • pulsar://my-broker:6650 for regular endpoint
      • pulsar+ssl://my-broker:6651 for TLS encrypted endpoint
      Parameters:
      serviceUrl - the URL of the Pulsar service that the client should connect to
      Returns:
      the client builder instance
    • serviceUrlProvider

      ClientBuilder serviceUrlProvider(ServiceUrlProvider serviceUrlProvider)
      Configure the service URL provider for Pulsar service.

      Instead of specifying a static service URL string (with serviceUrl(String)), an application can pass a ServiceUrlProvider instance that dynamically provide a service URL.

      Parameters:
      serviceUrlProvider - the provider instance
      Returns:
      the client builder instance
    • listenerName

      ClientBuilder listenerName(String name)
      Configure the listenerName that the broker will return the corresponding `advertisedListener`.
      Parameters:
      name - the listener name
      Returns:
      the client builder instance
    • authentication

      ClientBuilder authentication(Authentication authentication)
      Set the authentication provider to use in the Pulsar client instance.

      Example:

      
       PulsarClient client = PulsarClient.builder()
               .serviceUrl("pulsar+ssl://broker.example.com:6651/")
               .authentication(
                     AuthenticationFactory.TLS("/my/cert/file", "/my/key/file")
               .build();
       

      For token based authentication, this will look like:

      
       AuthenticationFactory
            .token("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJKb2UifQ.ipevRNuRP6HflG8cFKnmUPtypruRC4fb1DWtoLL62SY")
       
      Parameters:
      authentication - an instance of the Authentication provider already constructed
      Returns:
      the client builder instance
    • authentication

      ClientBuilder authentication(String authPluginClassName, String authParamsString) throws PulsarClientException.UnsupportedAuthenticationException
      Configure the authentication provider to use in the Pulsar client instance.

      Example:

       
       PulsarClient client = PulsarClient.builder()
                .serviceUrl("pulsar+ssl://broker.example.com:6651/)
                .authentication(
                    "org.apache.pulsar.client.impl.auth.AuthenticationTls",
                    "tlsCertFile:/my/cert/file,tlsKeyFile:/my/key/file")
                .build();
       
       
      Parameters:
      authPluginClassName - name of the Authentication-Plugin you want to use
      authParamsString - string which represents parameters for the Authentication-Plugin, e.g., "key1:val1,key2:val2"
      Returns:
      the client builder instance
      Throws:
      PulsarClientException.UnsupportedAuthenticationException - failed to instantiate specified Authentication-Plugin
    • authentication

      ClientBuilder authentication(String authPluginClassName, Map<String,String> authParams) throws PulsarClientException.UnsupportedAuthenticationException
      Configure the authentication provider to use in the Pulsar client instance using a config map.

      Example:

      
       Map<String, String> conf = new TreeMap<>();
       conf.put("tlsCertFile", "/my/cert/file");
       conf.put("tlsKeyFile", "/my/key/file");
      
       PulsarClient client = PulsarClient.builder()
                .serviceUrl("pulsar+ssl://broker.example.com:6651/)
                .authentication(
                    "org.apache.pulsar.client.impl.auth.AuthenticationTls", conf)
                .build();
       
      Parameters:
      authPluginClassName - name of the Authentication-Plugin you want to use
      authParams - map which represents parameters for the Authentication-Plugin
      Returns:
      the client builder instance
      Throws:
      PulsarClientException.UnsupportedAuthenticationException - failed to instantiate specified Authentication-Plugin
    • operationTimeout

      ClientBuilder operationTimeout(int operationTimeout, TimeUnit unit)
      Set the operation timeout (default: 30 seconds).

      Producer-create, subscribe and unsubscribe operations will be retried until this interval, after which the operation will be marked as failed

      Parameters:
      operationTimeout - operation timeout
      unit - time unit for operationTimeout
      Returns:
      the client builder instance
    • lookupTimeout

      ClientBuilder lookupTimeout(int lookupTimeout, TimeUnit unit)
      Set lookup timeout (default: matches operation timeout) Lookup operations have a different load pattern to other operations. They can be handled by any broker, are not proportional to throughput, and are harmless to retry. Given this, it makes sense to allow them to retry longer than normal operation, especially if they experience a timeout. By default this is set to match operation timeout. This is to maintain legacy behaviour. However, in practice it should be set to 5-10x the operation timeout.
      Parameters:
      lookupTimeout - lookup timeout
      unit - time unit for lookupTimeout
      Returns:
      the client builder instance
    • ioThreads

      ClientBuilder ioThreads(int numIoThreads)
      Set the number of threads to be used for handling connections to brokers (default: 1 thread).
      Parameters:
      numIoThreads - the number of IO threads
      Returns:
      the client builder instance
    • listenerThreads

      ClientBuilder listenerThreads(int numListenerThreads)
      Set the number of threads to be used for message listeners (default: 1 thread).

      The listener thread pool is shared across all the consumers and readers that are using a "listener" model to get messages. For a given consumer, the listener will be always invoked from the same thread, to ensure ordering.

      Parameters:
      numListenerThreads - the number of listener threads
      Returns:
      the client builder instance
    • connectionsPerBroker

      ClientBuilder connectionsPerBroker(int connectionsPerBroker)
      Sets the max number of connection that the client library will open to a single broker.

      By default, the connection pool will use a single connection for all the producers and consumers. Increasing this parameter may improve throughput when using many producers over a high latency connection.

      Parameters:
      connectionsPerBroker - max number of connections per broker (needs to be greater than or equal to 0)
      Returns:
      the client builder instance
    • enableTcpNoDelay

      ClientBuilder enableTcpNoDelay(boolean enableTcpNoDelay)
      Configure whether to use TCP no-delay flag on the connection, to disable Nagle algorithm.

      No-delay features make sure packets are sent out on the network as soon as possible, and it's critical to achieve low latency publishes. On the other hand, sending out a huge number of small packets might limit the overall throughput, so if latency is not a concern, it's advisable to set the useTcpNoDelay flag to false.

      Default value is true.

      Parameters:
      enableTcpNoDelay - whether to enable TCP no-delay feature
      Returns:
      the client builder instance
    • enableTls

      @Deprecated ClientBuilder enableTls(boolean enableTls)
      Deprecated.
      use "pulsar+ssl://" in serviceUrl to enable
      Configure whether to use TLS encryption on the connection (default: true if serviceUrl starts with "pulsar+ssl://", false otherwise).
      Parameters:
      enableTls -
      Returns:
      the client builder instance
    • tlsTrustCertsFilePath

      ClientBuilder tlsTrustCertsFilePath(String tlsTrustCertsFilePath)
      Set the path to the trusted TLS certificate file.
      Parameters:
      tlsTrustCertsFilePath -
      Returns:
      the client builder instance
    • allowTlsInsecureConnection

      ClientBuilder allowTlsInsecureConnection(boolean allowTlsInsecureConnection)
      Configure whether the Pulsar client accept untrusted TLS certificate from broker (default: false).
      Parameters:
      allowTlsInsecureConnection - whether to accept a untrusted TLS certificate
      Returns:
      the client builder instance
    • enableTlsHostnameVerification

      ClientBuilder enableTlsHostnameVerification(boolean enableTlsHostnameVerification)
      It allows to validate hostname verification when client connects to broker over tls. It validates incoming x509 certificate and matches provided hostname(CN/SAN) with expected broker's host name. It follows RFC 2818, 3.1. Server Identity hostname verification.
      Parameters:
      enableTlsHostnameVerification - whether to enable TLS hostname verification
      Returns:
      the client builder instance
      See Also:
    • useKeyStoreTls

      ClientBuilder useKeyStoreTls(boolean useKeyStoreTls)
      If Tls is enabled, whether use KeyStore type as tls configuration parameter. False means use default pem type configuration.
      Parameters:
      useKeyStoreTls -
      Returns:
      the client builder instance
    • sslProvider

      ClientBuilder sslProvider(String sslProvider)
      The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.
      Parameters:
      sslProvider -
      Returns:
      the client builder instance
    • tlsTrustStoreType

      ClientBuilder tlsTrustStoreType(String tlsTrustStoreType)
      The file format of the trust store file.
      Parameters:
      tlsTrustStoreType -
      Returns:
      the client builder instance
    • tlsTrustStorePath

      ClientBuilder tlsTrustStorePath(String tlsTrustStorePath)
      The location of the trust store file.
      Parameters:
      tlsTrustStorePath -
      Returns:
      the client builder instance
    • tlsTrustStorePassword

      ClientBuilder tlsTrustStorePassword(String tlsTrustStorePassword)
      The store password for the key store file.
      Parameters:
      tlsTrustStorePassword -
      Returns:
      the client builder instance
    • tlsCiphers

      ClientBuilder tlsCiphers(Set<String> tlsCiphers)
      A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.
      Parameters:
      tlsCiphers -
      Returns:
      the client builder instance
    • tlsProtocols

      ClientBuilder tlsProtocols(Set<String> tlsProtocols)
      The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.3, TLSv1.2 and TLSv1.1.
      Parameters:
      tlsProtocols -
      Returns:
      the client builder instance
    • memoryLimit

      ClientBuilder memoryLimit(long memoryLimit, SizeUnit unit)
      Configure a limit on the amount of direct memory that will be allocated by this client instance.

      Note: at this moment this is only limiting the memory for producers.

      Setting this to 0 will disable the limit.

      Parameters:
      memoryLimit - the limit
      unit - the memory limit size unit
      Returns:
      the client builder instance
    • statsInterval

      ClientBuilder statsInterval(long statsInterval, TimeUnit unit)
      Set the interval between each stat info (default: 60 seconds) Stats will be activated with positive statsInterval It should be set to at least 1 second.
      Parameters:
      statsInterval - the interval between each stat info
      unit - time unit for statsInterval
      Returns:
      the client builder instance
    • maxConcurrentLookupRequests

      ClientBuilder maxConcurrentLookupRequests(int maxConcurrentLookupRequests)
      Number of concurrent lookup-requests allowed to send on each broker-connection to prevent overload on broker. (default: 5000) It should be configured with higher value only in case of it requires to produce/subscribe on thousands of topic using created PulsarClient.
      Parameters:
      maxConcurrentLookupRequests -
      Returns:
      the client builder instance
    • maxLookupRequests

      ClientBuilder maxLookupRequests(int maxLookupRequests)
      Number of max lookup-requests allowed on each broker-connection to prevent overload on broker. (default: 50000) It should be bigger than maxConcurrentLookupRequests. Requests that inside maxConcurrentLookupRequests already send to broker, and requests beyond maxConcurrentLookupRequests and under maxLookupRequests will wait in each client cnx.
      Parameters:
      maxLookupRequests -
      Returns:
      the client builder instance
    • maxLookupRedirects

      ClientBuilder maxLookupRedirects(int maxLookupRedirects)
      Set the maximum number of times a lookup-request to a broker will be redirected.
      Parameters:
      maxLookupRedirects - the maximum number of redirects
      Returns:
      the client builder instance
      Since:
      2.6.0
    • maxNumberOfRejectedRequestPerConnection

      ClientBuilder maxNumberOfRejectedRequestPerConnection(int maxNumberOfRejectedRequestPerConnection)
      Set max number of broker-rejected requests in a certain time-frame (30 seconds) after which current connection will be closed and client creates a new connection that give chance to connect a different broker (default: 50).
      Parameters:
      maxNumberOfRejectedRequestPerConnection -
      Returns:
      the client builder instance
    • keepAliveInterval

      ClientBuilder keepAliveInterval(int keepAliveInterval, TimeUnit unit)
      Set keep alive interval for each client-broker-connection. (default: 30 seconds).
      Parameters:
      keepAliveInterval -
      unit - the time unit in which the keepAliveInterval is defined
      Returns:
      the client builder instance
    • connectionTimeout

      ClientBuilder connectionTimeout(int duration, TimeUnit unit)
      Set the duration of time to wait for a connection to a broker to be established. If the duration passes without a response from the broker, the connection attempt is dropped.
      Parameters:
      duration - the duration to wait
      unit - the time unit in which the duration is defined
      Returns:
      the client builder instance
      Since:
      2.3.0
    • startingBackoffInterval

      ClientBuilder startingBackoffInterval(long duration, TimeUnit unit)
      Set the duration of time for a backoff interval.
      Parameters:
      duration - the duration of the interval
      unit - the time unit in which the duration is defined
      Returns:
      the client builder instance
    • maxBackoffInterval

      ClientBuilder maxBackoffInterval(long duration, TimeUnit unit)
      Set the maximum duration of time for a backoff interval.
      Parameters:
      duration - the duration of the interval
      unit - the time unit in which the duration is defined
      Returns:
      the client builder instance
    • enableBusyWait

      ClientBuilder enableBusyWait(boolean enableBusyWait)
      Option to enable busy-wait settings. Default is false. WARNING: This option will enable spin-waiting on executors and IO threads in order to reduce latency during context switches. The spinning will consume 100% CPU even when the broker is not doing any work. It is recommended to reduce the number of IO threads and BK client threads to only have few CPU cores busy.
      Parameters:
      enableBusyWait - whether to enable busy wait
      Returns:
      the client builder instance
    • clock

      ClientBuilder clock(Clock clock)
      The clock used by the pulsar client.

      The clock is currently used by producer for setting publish timestamps. Clock.millis() is called to retrieve current timestamp as the publish timestamp when producers produce messages. The default clock is a system default zone clock. So the publish timestamp is same as calling System.currentTimeMillis().

      Warning: the clock is used for TTL enforcement and timestamp based seeks. so be aware of the impacts if you are going to use a different clock.

      Parameters:
      clock - the clock used by the pulsar client to retrieve time information
      Returns:
      the client builder instance
    • proxyServiceUrl

      ClientBuilder proxyServiceUrl(String proxyServiceUrl, ProxyProtocol proxyProtocol)
      Proxy-service url when client would like to connect to broker via proxy. Client can choose type of proxy-routing using ProxyProtocol.
      Parameters:
      proxyServiceUrl - proxy service url
      proxyProtocol - protocol to decide type of proxy routing eg: SNI-routing
      Returns:
    • enableTransaction

      ClientBuilder enableTransaction(boolean enableTransaction)
      If enable transaction, start the transactionCoordinatorClient with pulsar client.
      Parameters:
      enableTransaction - whether enable transaction feature
      Returns:
    • dnsLookupBind

      ClientBuilder dnsLookupBind(String address, int port)
      Set dns lookup bind address and port.
      Parameters:
      address - dnsBindAddress
      port - dnsBindPort
      Returns:
    • socks5ProxyAddress

      ClientBuilder socks5ProxyAddress(InetSocketAddress socks5ProxyAddress)
      Set socks5 proxy address.
      Parameters:
      socks5ProxyAddress -
      Returns:
    • socks5ProxyUsername

      ClientBuilder socks5ProxyUsername(String socks5ProxyUsername)
      Set socks5 proxy username.
      Parameters:
      socks5ProxyUsername -
      Returns:
    • socks5ProxyPassword

      ClientBuilder socks5ProxyPassword(String socks5ProxyPassword)
      Set socks5 proxy password.
      Parameters:
      socks5ProxyPassword -
      Returns: