title: How to connect to Gremlin Server through Java using the Gremlin Driver with sessionless
body: <p>I want my application to connect to two remote servers Gremlinserver/Janusserver.Both have the same Cassandra database. 
  And in this way thatI would have high availability.</p>
  
  <pre><code>&lt;dependency&gt;
      &lt;groupId&gt;org.janusgraph&lt;/groupId&gt;
      &lt;artifactId&gt;janusgraph-core&lt;/artifactId&gt;
      &lt;version&gt;0.2.0&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;org.apache.tinkerpop&lt;/groupId&gt;
      &lt;artifactId&gt;gremlin-driver&lt;/artifactId&gt;
      &lt;version&gt;3.2.6&lt;/version&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p>file gremlin.yaml:</p>
  
  <pre><code>hosts: [127.0.0.1,192.168.2.57]
  port: 8182
  serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { serializeResultToString: true }}
  </code></pre>
  
  <p>In my service class I have several methods, each of which connects through the client object:</p>
  
  <pre><code>public class GremlinServiceConcrete implements GremlinService {
  ...
  ..
  public Set&lt;Long&gt; getImpactedComponentsIds (...) throws GremlinServiceException {
  ..
          Cluster cluster = gremlinCluster.getCluster();
          Client client = null;
          Set&lt;Long&gt; impactedIds = Sets.newHashSet();
          try {
              client = cluster.connect();
              binding = Maps.newLinkedHashMap();
  ..
  </code></pre>
  
  <p>And in the GremlinCluster Class, I call the driver</p>
  
  <pre><code>public class GremlinCluster {
  
      public static final int MIN_CONNECTION_POOL_SIZE = 2;
      public static final int MAX_CONNECTION_POOL_SIZE = 20;
      public static final int MAX_CONTENT_LENGTH = 65536000;
  
      private static Logger logger = LoggerFactory.getLogger(GremlinCluster.class);
  
      private String server;
      private Integer port;
  
      private Cluster cluster;
  
      public GremlinCluster(String server, Integer port) throws FileNotFoundException {
          this.server = Objects.requireNonNull(server);
          this.port = Objects.requireNonNull(port);
          this.cluster = init();
      }
  
      private Cluster init() throws FileNotFoundException {
          GryoMapper.Builder kryo = GryoMapper.build().addRegistry(JanusGraphIoRegistry.getInstance());
          MessageSerializer serializer = new GryoMessageSerializerV1d0(kryo);
          Cluster cluster = Cluster.build(new File("conf/driver-gremlin.yaml")).port(port)
                  .serializer(serializer)
                  .minConnectionPoolSize(MIN_CONNECTION_POOL_SIZE)
                  .maxConnectionPoolSize(MAX_CONNECTION_POOL_SIZE)
                  .maxContentLength(MAX_CONTENT_LENGTH).create();
  
          logger.debug(String.format("New cluster connected at %s:%s", server, port));
          return cluster;
      }
  
      public Cluster getCluster() {
          return cluster;
      }
  
      public void destroy() {
          try {
              cluster.close();
          } catch (Exception e) {
              logger.debug("Error closing cluster connection: " + e.toString());
          }
      }
  
  }
  </code></pre>
  
  <p>The application works well by connecting to only one server.
  When you connect to the servers it runs very slow. If I stop a server does not run failover correctly
  I suspect that the servers are connected in session mode.
  The Tinkerpop documentation does not specify the code differences between the two modes.</p>
  
  <p>Correction:
  The slowness was due to the debug mode of eclipse.
  The application sends requests to both gremlinservers, this part of the clustering functionality works fine.</p>
  
  <p>Incorrect operation happens when a server is shutdown. The application sends the requests to the other server. If the downed server is booted, the gremlin server does not detect it and does not reconnect.</p>
  
  <p>output from gremlinserver:
  <a href="https://i.stack.imgur.com/lUNDo.png" rel="nofollow noreferrer">enter image description here</a></p>
  
  <p>GremlinCluster is a spring bean (beans-services.xml):</p>
  
  <pre><code>&lt;bean id="gremlinCluster" class="[Fully qualified name].GremlinCluster" scope="singleton" destroy-method="destroy"&gt;
      &lt;constructor-arg name="server"&gt;&lt;value&gt;${GremlinServerHost}&lt;/value&gt;&lt;/constructor-arg&gt;
      &lt;constructor-arg name="port"&gt;&lt;value&gt;${GremlinServerPort}&lt;/value&gt;&lt;/constructor-arg&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>And in a property file.</p>
  
  <pre><code>GremlinServerHost=[Fully qualified name]/config/gremlin.yaml
  GremlinServerPort=8182
  </code></pre>
  
  <p>And in the GremlinCluster Class:</p>
  
  <pre><code>import java.util.Objects;
  
  import org.apache.tinkerpop.gremlin.driver.Cluster;
  import org.apache.tinkerpop.gremlin.driver.MessageSerializer;
  import org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0;
  import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoMapper;
  import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import java.io.File;
  import java.io.FileNotFoundException;
  
  public class GremlinCluster {
  
      public static final int MIN_CONNECTION_POOL_SIZE = 2;
      public static final int MAX_CONNECTION_POOL_SIZE = 20;
      public static final int MAX_CONTENT_LENGTH = 65536000;
  
      private static Logger logger = LoggerFactory.getLogger(GremlinCluster.class);
  
      private String server;
      private Integer port;
  
      private Cluster cluster;
  
      public GremlinCluster(String server, Integer port) throws FileNotFoundException {
          this.server = Objects.requireNonNull(server);
          this.port = Objects.requireNonNull(port);
          this.cluster = init();
      }
  
      private Cluster init() throws FileNotFoundException {
          GryoMapper.Builder kryo = GryoMapper.build().addRegistry(JanusGraphIoRegistry.getInstance());
          MessageSerializer serializer = new GryoMessageSerializerV1d0(kryo);
          Cluster cluster = Cluster.build(new File(server)).port(port)
                  .serializer(serializer)
                  .minConnectionPoolSize(MIN_CONNECTION_POOL_SIZE)
                  .maxConnectionPoolSize(MAX_CONNECTION_POOL_SIZE)
                  .maxContentLength(MAX_CONTENT_LENGTH).create();
  
          logger.debug(String.format("New cluster connected at %s:%s", server, port));
          return cluster;
      }
  
      public Cluster getCluster() {
          return cluster;
      }
  
      public void destroy() {
          try {
              cluster.close();
          } catch (Exception e) {
              logger.debug("Error closing cluster connection: " + e.toString());
          }
      }
  
  }
  </code></pre>
  
  <p>And a example with a method that makes a query (GremlinServiceConcrete): </p>
  
  <pre><code>@Override
      public Long getNeighborsCount(List&lt;Long&gt; componentIds) throws GremlinServiceException {
          // Check argument is right
          if (componentIds == null || componentIds.isEmpty()) {
              throw new GremlinServiceException("Cannot compute neighbors count with an empty list as argument");
          }
  
          Cluster cluster = gremlinCluster.getCluster();
          Client client = null;
          try {
              client = cluster.connect();
              String gremlin = "g.V(componentIds).both().dedup().count()";
              Map&lt;String, Object&gt; parameters = Maps.newHashMap();
              parameters.put("componentIds", componentIds);
  
              if (logger.isDebugEnabled()) logger.debug("Submiting query [ " + gremlin + " ] with binding [ " + parameters + "]");
  
              ResultSet resultSet = client.submit(gremlin, parameters);
              Result result = resultSet.one();
              return result.getLong();
  
          } catch (Exception e) {
              throw new GremlinServiceException("Error retrieving how many neighbors do vertices " + componentIds + " have: " + e.getMessage(), e);
  
          } finally {
              if (client != null) try { client.close(); } catch (Exception e) { /* NPE because connection was not initialized yet */ }
          }
      }
  </code></pre>
  
  <p>gremlin-server.yaml:</p>
  
  <pre><code>host: 127.0.0.1
  port: 8182
  scriptEvaluationTimeout: 600000
  channelizer: org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer
  graphs: {
    graph: conf/janusgraph-cassandra.properties
  }
  plugins:
    - janusgraph.imports
  scriptEngines: {
    gremlin-groovy: {
      imports: [java.lang.Math,org.janusgraph.core.schema.Mapping],
      staticImports: [java.lang.Math.PI],
      scripts: [scripts/empty-sample.groovy]}}
  serializers:
    - {
        className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0,
        config: {
          bufferSize: 819200,
          ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry]
        }
      }
    - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoLiteMessageSerializerV1d0, config: {ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
    - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { serializeResultToString: true }}
    - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistryV1d0] }}
    - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV2d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
    - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistryV1d0] }}
  processors:
    - { className: org.apache.tinkerpop.gremlin.server.op.session.SessionOpProcessor, config: { sessionTimeout: 28800000 }}
    - { className: org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor, config: { cacheExpirationTime: 600000, cacheMaxSize: 1000 }}
  metrics: {
    consoleReporter: {enabled: true, interval: 180000},
    csvReporter: {enabled: true, interval: 180000, fileName: /tmp/gremlin-server-metrics.csv},
    jmxReporter: {enabled: true},
    slf4jReporter: {enabled: true, interval: 180000},
    gangliaReporter: {enabled: false, interval: 180000, addressingMode: MULTICAST},
    graphiteReporter: {enabled: false, interval: 180000}}
  maxInitialLineLength: 4096
  maxHeaderSize: 8192
  maxChunkSize: 4096000
  maxContentLength: 65536000
  maxAccumulationBufferComponents: 1024
  resultIterationBatchSize: 64
  writeBufferLowWaterMark: 32768
  writeBufferHighWaterMark: 655360
  </code></pre>
  
  <p>janusgraph-cassandra.properties:</p>
  
  <pre><code>gremlin.graph=org.janusgraph.core.JanusGraphFactory
  storage.backend=cassandrathrift
  storage.hostname=192.168.2.57,192.168.2.70,192.168.2.77
  cache.db-cache = true
  cache.db-cache-clean-wait = 20
  cache.db-cache-time = 180000
  cache.db-cache-size = 0.5
  #storage.cassandra.replication-strategy-class=org.apache.cassandra.locator.NetworkTopologyStrategy
  #storage.cassandra.replication-strategy-options=dc1,2,dc2,1
  storage.cassandra.read-consistency-level=QUORUM
  storage.cassandra.write-consistency-level=QUORUM
  ids.authority.conflict-avoidance-mode=GLOBAL_AUTO
  </code></pre>