1

I have an app built with Javalin (a simple HTTP framework in Java) that leverages Cassandra as the backend.

According to Datastax docs https://docs.datastax.com/en/developer/java-driver/4.9/manual/core/#quick-start

CqlSession is the main entry point of the driver. It holds the known state of the actual Cassandra cluster, and is what you use to execute queries. It is thread-safe, you should create a single instance (per target Cassandra cluster), and share it throughout your application;

This is what my main function looks like:

  public static void main(String[] args) {
    CqlSession cqlSession = CqlSession.builder().build();
    runCassandraMigration(cqlSession);
    Javalin app =
        Javalin.create(config -> config.registerPlugin(new OpenApiPlugin(getOpenApiOptions())))
            .start(PORT);
    Handlers handlers = new Handlers(cqlSession);
    registerAppRoutes(app, handlers);
  }

The Handlers class include handle function like below:

public class Handlers {
  private final CqlSession session;
  
  public Context getAllUsers(Context ctx) {
    ResultSet rs = session.execute("select * from my_status.users");
    List<Row> rows = rs.all();
    return ctx.json(rows.stream().map(this::rowToUser).collect(Collectors.toList()));
  }
}

However, after I start the application, and hit the REST endpoint locally, I got

java.lang.IllegalStateException: Session is closed

I want to know how to create a long-lived CqlSession rather than per-request short-lived ones. The app I am working on can be found in https://github.com/YikSanChan/mystatus/tree/main/api/src/main/java.

yiksanchan
  • 1,890
  • 1
  • 13
  • 37
  • The code on that GitHub repo doesn't look like what you posted. I believe that the code you posted should work fine. The session isn't being closed so I don't think it is possible to even get that exception in that case, are you sure that you weren't using something like "try (CqlSession session = CqlSession.builder().build()) { }"? – João Reis Feb 18 '21 at 11:44
  • @Yik Scan Chan did you fixed your problem? – Jad Chahine Apr 21 '21 at 19:19
  • @JadChahine I didn't. Still haven't figured out – yiksanchan Apr 22 '21 at 02:59

0 Answers0