简体   繁体   中英

Handling Datastax Java driver CqlSession in Spring Boot

Datastax Java driver documentation says to create a single instance of CqlSession for your Spring Boot application as building a session is a costly operation.

I want to manage the CqlSession in an effective way in Spring Boot such that CqlSession instance should be closed and not kept open in order to free underlying resources(TCP connections, thread pools…).

Driver documentation URL: https://docs.datastax.com/en/developer/java-driver/4.13/manual/core/

Here is my CqlSession Instance class. I use the Cqlsession instance to run Cql queries all over my Spring Boot application by injecting it as a Dependency in my @Service and @Repository classes.

Also I never close my Cql session manually but let the Spring handle it using @PreDestory annotation. Should session be closed as soon as a cql query is executed or should I allow spring to handle it as mentioned in the below code? I have realised that doing so, it takes a latency about 1-1.5 seconds for building cqlsession again and queries are ran super slow due to this.

@Configuration 
public class CqlSessionInstance {
    
        private CqlSession session;
    
        @PostConstruct
        private void initSession() {
            getSession();
        }
    
        public final CqlSession getSession() {
            if(session == null || session.isClosed()) {
                session = CqlSession.builder().build();
            }
            return session;
        }
    
        @PreDestroy
        public final void closeSession() {
            if (session != null && !session.isClosed()) session.close();
        }
    
    }

Let me know if there are better ways to manage a CqlSession in Spring Boot

In my opinion, I suggest that you close the CqlSession yourself, since you know when you are executing as a specific request, and you know when to close it.

If you use the annotation @PreDestroy , you are depending on the Spring Life Cycle Management and as such it is hard to determine "when" exactly your component will be destroyed, and as such your session closed.

I am stuck in same dilemma, when to close session? at pre destroy or after each request?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM