private Void handleConnectionError(Throwable exception) { log.warn("[{}] [{}] Error connecting to broker: {}", topic, getHandlerName(), exception.getMessage()); connectionFailed(new PulsarClientException(exception)); State state = STATE_UPDATER.get(this); if (state == State.Uninitialized || state == State.Connecting || state == State.Ready) { reconnectLater(exception); } return null; }
protected void reconnectLater(Throwable exception) { CLIENT_CNX_UPDATER.set(this, null); if (!isValidStateForReconnection()) { log.info("[{}] [{}] Ignoring reconnection request (state: {})", topic, getHandlerName(), STATE_UPDATER.get(this)); return; } long delayMs = backoff.next(); log.warn("[{}] [{}] Could not get connection to broker: {} -- Will try again in {} s", topic, getHandlerName(), exception.getMessage(), delayMs / 1000.0); STATE_UPDATER.set(this, State.Connecting); client.timer().newTimeout(timeout -> { log.info("[{}] [{}] Reconnecting after connection was closed", topic, getHandlerName()); grabCnx(); }, delayMs, TimeUnit.MILLISECONDS); }
protected void grabCnx() { if (CLIENT_CNX_UPDATER.get(this) != null) { log.warn("[{}] [{}] Client cnx already set, ignoring reconnection request", topic, getHandlerName()); return; } if (!isValidStateForReconnection()) { // Ignore connection closed when we are shutting down log.info("[{}] [{}] Ignoring reconnection request (state: {})", topic, getHandlerName(), STATE_UPDATER.get(this)); return; } try { client.getConnection(topic) // .thenAccept(this::connectionOpened) // .exceptionally(this::handleConnectionError); } catch (Throwable t) { log.warn("[{}] [{}] Exception thrown while getting connection: ", topic, getHandlerName(), t); reconnectLater(t); } }
protected void connectionClosed(ClientCnx cnx) { if (CLIENT_CNX_UPDATER.compareAndSet(this, cnx, null)) { if (!isValidStateForReconnection()) { log.info("[{}] [{}] Ignoring reconnection request (state: {})", topic, getHandlerName(), STATE_UPDATER.get(this)); return; } long delayMs = backoff.next(); STATE_UPDATER.set(this, State.Connecting); log.info("[{}] [{}] Closed connection {} -- Will try again in {} s", topic, getHandlerName(), cnx.channel(), delayMs / 1000.0); client.timer().newTimeout(timeout -> { log.warn("[{}] [{}] Reconnecting after timeout", topic, getHandlerName()); grabCnx(); }, delayMs, TimeUnit.MILLISECONDS); } }