Apache Cassandra and Java EE

In this Blog I will show you how we use Apache Cassandra in our Open Source Project Imixs-Archive. Imixs-Archive is a service which we use in Imixs-Workflow to push business data into a Cassandra Cluster. The service provides a Rest API based on JAX-RS and uses the DataStax Driver to write the data into the Cassandra Cluster.

The problem is that for a connection you need first to setup a Cluster Object and connect to your keyspace to get a Session object. This is time consuming and slows down the rest service call if you do this during the request. But within Java EE you can solve this problem easily

A Cassandra session object is intended to be a long-lived. You only need one session per cluster. So by implementing a Singleton CDI bean you can easily hold the session for multiple requests. The CDI bean can create the seisson on the first request and hold the session alive for further requests. Take a look at the following code example:

@Singleton
public class ClusterService {

	private Cluster cluster;
	private Session session;

	@PostConstruct
	private void init() throws ArchiveException {
		cluster=initCluster();
		session = initArchiveSession();
	}

	@PreDestroy
	private void tearDown() throws ArchiveException {
		// close session and cluster object
		if (session != null) {
			session.close();
		}
		if (cluster != null) {
			cluster.close();
		}
	}
	
	public Session getSession() {
		if (session==null) {
			try {
				init();
			} catch (ArchiveException e) {
				e.printStackTrace();
			}
		}
		return session;
	}
}

In your Rest API you can now simply inject the ClusterService Bean to get a valid session:

@Path("/archive")
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
@Stateless
public class ArchiveRestService {
	@Inject
	ClusterService clusterService;

        @Post
	@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_XML })
	public Response postSnapshot(Data ...) {
		Session session = clusterService.getSession();		
		try {
			session.execute(new SimpleStatement(...)));
			....
		} catch (ArchiveException e) {
			
		} 	
	}
}

Of course you can further extend this idea to have sessions per keyspace.

I hope this will help you to get succeeded with Apache Cassandra.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.