Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

datastax - How to create a long lived cassandra CqlSession in a Javalin app

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...