SlideShare a Scribd company logo
Cassandra for Java Developers 
DataStax Driver & DevCenter 
Michaël Figuière 
Drivers & Developer Tools Architect
Client / Server Communication 
© 2014 DataStax, All Rights Reserved. 
2 
Client 
Client 
Client 
Client 
Node 
Node Replica 
Replica 
Replica 
Node 
Coordinator node: 
Forwards all R/W requests 
to corresponding replicas
Request Pipelining 
© 2014 DataStax, All Rights Reserved. 
3 
Client 
Without 
Request Pipelining 
Cassandra 
Client Cassandra 
With 
Request Pipelining
Notifications 
© 2014 DataStax, All Rights Reserved. 
4 
Client 
Without 
Notifications 
With 
Notifications 
Node 
Node 
Node 
Client 
Node 
Node 
Node
Asynchronous Driver Architecture 
© 2014 DataStax, All Rights Reserved. 
5 
Client 
Thread 
Node 
Node 
Node 
Client 
Thread 
Client 
Thread 
Node 
Driver
Asynchronous Driver Architecture 
© 2014 DataStax, All Rights Reserved. 
6 
Client 
Thread 
Node 
Node 
Node 
Client 
Thread 
Client 
Thread 
Node 
6 
2 
3 
4 
5 
1 
Driver
Failover 
© 2014 DataStax, All Rights Reserved. 
7 
Client 
Thread 
Node 
Node 
Node 
Client 
Thread 
Client 
Thread 
Node 
7 
2 
4 
3 5 1 
Driver 
6
Java Driver Highlights 
• Reference implementation 
• Asynchronous architecture based on Netty 
• Prepared Statements Support 
• Automatic Failover 
• Node Discovery 
• Tunable Load Balancing 
• Round Robin, Latency Awareness, Multi Data Centers, Replica Awareness 
• Cassandra Tracing Support 
• Compression & SSL 
© 2014 DataStax, All Rights Reserved. 
8
DataCenter Aware Balancing 
© 2014 DataStax, All Rights Reserved. 
9 
Node 
Node 
Client Node 
Node 
Datacenter B 
Node 
Node 
Client 
Client 
Client 
Client 
Client 
Datacenter A 
Local nodes are queried 
first, if non are available, 
the request could be 
sent to a remote node.
Token Aware Balancing 
© 2014 DataStax, All Rights Reserved. 
Nodes that own a Replica 
of the PK being read or 
written by the query will 
be contacted first. 
10 
Node 
Node 
Replica 
Node 
Client 
Replica 
Replica 
Partition Key will be 
inferred from Prepared 
Statements metadata
DataStax Driver in Practice 
<dependency> 
<groupId>com.datastax.cassandra</groupId> 
<artifactId>cassandra-­‐driver-­‐core</artifactId> 
<version>2.1.0</version> 
</dependency> 
Available in Maven 
Central. Depends on 
Netty, Guava, Metrics 
Supports Apache Cassandra 1.2 to 2.1 
© 2014 DataStax, All Rights Reserved. 11
Connect and Write 
Cluster cluster = Cluster.builder() 
.addContactPoints("10.1.2.5", "cassandra_node3") 
.build(); 
Session session = cluster.connect(“my_keyspace"); 
session.execute( 
"INSERT INTO user (user_id, name, email) 
VALUES (12345, 'johndoe', 'john@doe.com')" 
); 
The rest of the 
nodes will be 
discovered by 
the driver 
A keyspace is 
just like a 
schema in the 
SQL world 
© 2014 DataStax, All Rights Reserved. 12
Read 
ResultSet resultSet = session.execute( 
Session is a thread safe 
object. A singleton should 
be instantiated at startup 
"SELECT * FROM user WHERE user_id IN (1,8,13)" 
); 
List<Row> rows = resultSet.all(); 
for (Row row : rows) { 
String userId = row.getString("user_id"); 
String name = row.getString("name"); 
String email = row.getString("email"); 
} 
Actually ResultSet also 
implements Iterable<Row> 
© 2014 DataStax, All Rights Reserved. 13
Write with Prepared Statements 
PreparedStatement objects 
are also threadsafe, just create 
a singleton at startup 
PreparedStatement insertUser = session.prepare( 
"INSERT INTO user (user_id, name, email) 
VALUES (?, ?, ?)" 
); 
BoundStatement statement = insertUser 
.bind(12345, "johndoe", "john@doe.com") 
.setConsistencyLevel(ConsistencyLevel.QUORUM); 
session.execute(statement); 
Parameters can 
be named as well 
BoundStatement 
is a stateful, NON 
threadsafe object 
Consistency Level can be 
set for each statement 
© 2014 DataStax, All Rights Reserved. 14
Asynchronous Read 
ResultSetFuture future = session.executeAsync( 
"SELECT * FROM user WHERE user_id IN (1,2,3)" 
); 
ResultSet resultSet = future.get(); 
List<Row> rows = resultSet.all(); 
for (Row row : rows) { 
String userId = row.getString("user_id"); 
String name = row.getString("name"); 
String email = row.getString("email"); 
} 
Will not block. Returns 
immediately 
Will block until less all 
the connections are 
busy 
© 2014 DataStax, All Rights Reserved. 15
Asynchronous Read with Callbacks 
ResultSetFuture future = session.executeAsync( 
"SELECT * FROM user WHERE user_id IN (1,2,3)" 
); 
future.addListener(new Runnable() { 
public void run() { 
// Process the results here 
} 
}, executor); 
ResultSetFuture 
implements Guava’s 
ListenableFuture 
executor = 
Executors 
.newCachedThreadPool(); 
executor = 
MoreExecutors 
.sameThreadExecutor(); 
Only if your listener code 
is trivial and non blocking 
as it’ll be executed in the 
IO Thread 
…Or any thread pool that 
you prefer 
© 2014 DataStax, All Rights Reserved. 16
Query Builder 
import static of 
QueryBuilder is required in 
order to use the DSL 
import static 
com.datastax.driver.core.querybuilder.QueryBuilder.*; 
Statement selectAll = 
select().all().from("user").where(eq("user_id", userId)); 
session.execute(selectAll); 
Statement insert = insertInto("user") 
.value("user_id", 2) 
.value("name", "johndoe") 
.value("email", "john@doe.com"); 
session.execute(insert); 
© 2014 DataStax, All Rights Reserved. 17
Object Mapper 
• Avoid boilerplate for common use cases 
• Map Objects to Statements and ResultSets to Objects 
• Do NOT hide Cassandra from the developer 
• No “clever tricks” à la Hibernate 
• Not JPA compatible, but JPA-ish API 
© 2014 DataStax, All Rights Reserved. 
18
Object Mapper in Practice 
<dependency> 
<groupId>com.datastax.cassandra</groupId> 
<artifactId>cassandra-­‐driver-­‐mapping</artifactId> 
<version>2.1.0</version> 
</dependency> 
Additional artifact for 
object mapping 
Available from Driver 2.1.0 
© 2014 DataStax, All Rights Reserved. 19
Basic Object Mapping 
CREATE 
TYPE 
address 
( 
street 
text, 
city 
text, 
zip 
int 
); 
CREATE 
TABLE 
users 
( 
email 
text 
PRIMARY 
KEY, 
address 
address 
); 
@UDT(keyspace 
= 
"ks", 
name 
= 
"address") 
public 
class 
Address 
{ 
private 
String 
street; 
private 
String 
city; 
private 
int 
zip; 
// 
getters 
and 
setters 
omitted... 
} 
@Table(keyspace 
= 
"ks", 
name 
= 
"users") 
public 
class 
User 
{ 
@PartitionKey 
private 
String 
email; 
private 
Address 
address; 
// 
getters 
and 
setters 
omitted... 
} 
© 2014 DataStax, All Rights Reserved. 20
Basic Object Mapping 
MappingManager 
manager 
= 
new 
MappingManager(session); 
Mapper 
mapper 
= 
manager.mapper(User.class); 
UserProfile 
myProfile 
= 
mapper.get("xyz@example.com"); 
ListenableFuture 
saveFuture 
= 
mapper.saveAsync(anotherProfile); 
mapper.delete("xyz@example.com"); 
Mapper, just like Session, is 
a thread-safe object. Create 
a singleton at startup. 
get() returns a mapped row 
for the given Primary Key 
ListenableFuture from 
Guava. Completed when the 
write is acknowledged. 
© 2014 DataStax, All Rights Reserved. 21
Accessors 
@Accessor 
interface 
UserAccessor 
{ 
@Query("SELECT 
* 
FROM 
user_profiles 
LIMIT 
:max") 
Result<User> 
firstN(@Param("max") 
int 
limit); 
} 
UserAccessor 
accessor 
= 
manager.createAccessor(UserAccessor.class); 
Result<User> 
users 
= 
accessor.firstN(10); 
for 
(User 
user 
: 
users) 
{ 
System.out.println( 
profile.getAddress().getZip() 
); 
} 
Result is like ResultSet 
but specialized for a 
mapped class… 
…so we iterate over it 
just like we would with a 
ResultSet 
© 2014 DataStax, All Rights Reserved. 22
DataStax DevCenter 
Demo
We’re Hiring! 
github.com/datastax 
blog.datastax.com 
@mfiguiere 
…seriously I really mean 
it, so if you’re passionated 
about beautiful technology 
feel free to talk to me! 
Work remotely from 
anywhere in Europe, 
even Luxembourg…

More Related Content

What's hot (19)

PDF
Apache ZooKeeper
Scott Leberknight
 
PPTX
Winter is coming? Not if ZooKeeper is there!
Joydeep Banik Roy
 
PDF
06 response-headers
snopteck
 
PDF
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Michaël Figuière
 
PPTX
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
DataStax Academy
 
PDF
Hazelcast
oztalip
 
PPTX
SCWCD : Thread safe servlets : CHAP : 8
Ben Abdallah Helmi
 
PDF
Cassandra 2.0 better, faster, stronger
Patrick McFadin
 
PPTX
High Throughput Analytics with Cassandra & Azure
DataStax Academy
 
PPTX
Jafka guide
Ady Liu
 
PDF
Ice mini guide
Ady Liu
 
PDF
Zookeeper
Geng-Dian Huang
 
PPTX
Async servers and clients in Rest.li
Karan Parikh
 
PPTX
Hazelcast
Bruno Lellis
 
PDF
Cassandra 3.0 advanced preview
Patrick McFadin
 
PDF
Php user groupmemcached
Jason Anderson
 
PDF
Beyond the Query: A Cassandra + Solr + Spark Love Triangle Using Datastax Ent...
DataStax Academy
 
PPTX
Hadoop Puzzlers
DataWorks Summit
 
PPTX
DevOpsDays Warsaw 2015: Running High Performance And Fault Tolerant Elasticse...
PROIDEA
 
Apache ZooKeeper
Scott Leberknight
 
Winter is coming? Not if ZooKeeper is there!
Joydeep Banik Roy
 
06 response-headers
snopteck
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Michaël Figuière
 
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
DataStax Academy
 
Hazelcast
oztalip
 
SCWCD : Thread safe servlets : CHAP : 8
Ben Abdallah Helmi
 
Cassandra 2.0 better, faster, stronger
Patrick McFadin
 
High Throughput Analytics with Cassandra & Azure
DataStax Academy
 
Jafka guide
Ady Liu
 
Ice mini guide
Ady Liu
 
Zookeeper
Geng-Dian Huang
 
Async servers and clients in Rest.li
Karan Parikh
 
Hazelcast
Bruno Lellis
 
Cassandra 3.0 advanced preview
Patrick McFadin
 
Php user groupmemcached
Jason Anderson
 
Beyond the Query: A Cassandra + Solr + Spark Love Triangle Using Datastax Ent...
DataStax Academy
 
Hadoop Puzzlers
DataWorks Summit
 
DevOpsDays Warsaw 2015: Running High Performance And Fault Tolerant Elasticse...
PROIDEA
 

Similar to YaJug - Cassandra for Java Developers (20)

PDF
Going native with Apache Cassandra
Johnny Miller
 
PPTX
DataStax NYC Java Meetup: Cassandra with Java
carolinedatastax
 
PDF
Cassandra Drivers and Tools
Duyhai Doan
 
PDF
Cassandra drivers and libraries
Duyhai Doan
 
PDF
Cassandra 2.0 to 2.1
Johnny Miller
 
PDF
Software Development with Apache Cassandra
zznate
 
PDF
Successful Software Development with Apache Cassandra
DataStax Academy
 
PDF
Paris Cassandra Meetup - Overview of New Cassandra Drivers
Michaël Figuière
 
PDF
C* Summit EU 2013: Cassandra Made Simple with CQL Drivers and DevCenter
DataStax Academy
 
PDF
Introduction to .Net Driver
DataStax Academy
 
PDF
Staying Ahead of the Curve with Spring and Cassandra 4 (SpringOne 2020)
Alexandre Dutra
 
PDF
Staying Ahead of the Curve with Spring and Cassandra 4
VMware Tanzu
 
PDF
Ruby Driver Explained: DataStax Webinar May 5th 2015
DataStax
 
PDF
Apache Cassandra and Drivers
DataStax Academy
 
PPTX
Microservices with Node.js and Apache Cassandra
Jorge Bay Gondra
 
PPTX
Lightning fast analytics with Cassandra and Spark
Victor Coustenoble
 
PDF
C* Summit 2013: Searching for a Needle in a Big Data Haystack by Jason Ruther...
DataStax Academy
 
PPTX
TDC2016SP - Trilha NoSQL
tdc-globalcode
 
PPTX
BI, Reporting and Analytics on Apache Cassandra
Victor Coustenoble
 
PDF
Python & Cassandra - Best Friends
Jon Haddad
 
Going native with Apache Cassandra
Johnny Miller
 
DataStax NYC Java Meetup: Cassandra with Java
carolinedatastax
 
Cassandra Drivers and Tools
Duyhai Doan
 
Cassandra drivers and libraries
Duyhai Doan
 
Cassandra 2.0 to 2.1
Johnny Miller
 
Software Development with Apache Cassandra
zznate
 
Successful Software Development with Apache Cassandra
DataStax Academy
 
Paris Cassandra Meetup - Overview of New Cassandra Drivers
Michaël Figuière
 
C* Summit EU 2013: Cassandra Made Simple with CQL Drivers and DevCenter
DataStax Academy
 
Introduction to .Net Driver
DataStax Academy
 
Staying Ahead of the Curve with Spring and Cassandra 4 (SpringOne 2020)
Alexandre Dutra
 
Staying Ahead of the Curve with Spring and Cassandra 4
VMware Tanzu
 
Ruby Driver Explained: DataStax Webinar May 5th 2015
DataStax
 
Apache Cassandra and Drivers
DataStax Academy
 
Microservices with Node.js and Apache Cassandra
Jorge Bay Gondra
 
Lightning fast analytics with Cassandra and Spark
Victor Coustenoble
 
C* Summit 2013: Searching for a Needle in a Big Data Haystack by Jason Ruther...
DataStax Academy
 
TDC2016SP - Trilha NoSQL
tdc-globalcode
 
BI, Reporting and Analytics on Apache Cassandra
Victor Coustenoble
 
Python & Cassandra - Best Friends
Jon Haddad
 
Ad

More from Michaël Figuière (17)

PDF
ApacheCon Europe 2012 - Real Time Big Data in practice with Cassandra
Michaël Figuière
 
PDF
NoSQL Matters 2012 - Real Time Big Data in practice with Cassandra
Michaël Figuière
 
PDF
GTUG Nantes (Dec 2011) - BigTable et NoSQL
Michaël Figuière
 
PDF
Duchess France (Nov 2011) - Atelier Apache Mahout
Michaël Figuière
 
PDF
JUG Summer Camp (Sep 2011) - Les applications et architectures d’entreprise d...
Michaël Figuière
 
PDF
BreizhCamp (Jun 2011) - Haute disponibilité et élasticité avec Cassandra
Michaël Figuière
 
PDF
Mix-IT (Apr 2011) - Intelligence Collective avec Apache Mahout
Michaël Figuière
 
PDF
Xebia Knowledge Exchange (mars 2011) - Machine Learning with Apache Mahout
Michaël Figuière
 
PDF
Breizh JUG (mar 2011) - NoSQL : Des Grands du Web aux Entreprises
Michaël Figuière
 
PDF
FOSDEM (feb 2011) - A real-time search engine with Lucene and S4
Michaël Figuière
 
PDF
Xebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Michaël Figuière
 
PDF
Xebia Knowledge Exchange (jan 2011) - Trends in Enterprise Applications Archi...
Michaël Figuière
 
PDF
Lorraine JUG (dec 2010) - NoSQL, des grands du Web aux entreprises
Michaël Figuière
 
PDF
Tours JUG (oct 2010) - NoSQL, des grands du Web aux entreprises
Michaël Figuière
 
PPTX
Paris JUG (sept 2010) - NoSQL : Des concepts à la réalité
Michaël Figuière
 
PPTX
Xebia Knowledge Exchange (mars 2010) - Lucene : From theory to real world
Michaël Figuière
 
PPTX
Xebia Knowledge Exchange (may 2010) - NoSQL : Using the right tool for the ri...
Michaël Figuière
 
ApacheCon Europe 2012 - Real Time Big Data in practice with Cassandra
Michaël Figuière
 
NoSQL Matters 2012 - Real Time Big Data in practice with Cassandra
Michaël Figuière
 
GTUG Nantes (Dec 2011) - BigTable et NoSQL
Michaël Figuière
 
Duchess France (Nov 2011) - Atelier Apache Mahout
Michaël Figuière
 
JUG Summer Camp (Sep 2011) - Les applications et architectures d’entreprise d...
Michaël Figuière
 
BreizhCamp (Jun 2011) - Haute disponibilité et élasticité avec Cassandra
Michaël Figuière
 
Mix-IT (Apr 2011) - Intelligence Collective avec Apache Mahout
Michaël Figuière
 
Xebia Knowledge Exchange (mars 2011) - Machine Learning with Apache Mahout
Michaël Figuière
 
Breizh JUG (mar 2011) - NoSQL : Des Grands du Web aux Entreprises
Michaël Figuière
 
FOSDEM (feb 2011) - A real-time search engine with Lucene and S4
Michaël Figuière
 
Xebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Michaël Figuière
 
Xebia Knowledge Exchange (jan 2011) - Trends in Enterprise Applications Archi...
Michaël Figuière
 
Lorraine JUG (dec 2010) - NoSQL, des grands du Web aux entreprises
Michaël Figuière
 
Tours JUG (oct 2010) - NoSQL, des grands du Web aux entreprises
Michaël Figuière
 
Paris JUG (sept 2010) - NoSQL : Des concepts à la réalité
Michaël Figuière
 
Xebia Knowledge Exchange (mars 2010) - Lucene : From theory to real world
Michaël Figuière
 
Xebia Knowledge Exchange (may 2010) - NoSQL : Using the right tool for the ri...
Michaël Figuière
 
Ad

Recently uploaded (20)

PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PDF
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
Digital water marking system project report
Kamal Acharya
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Design Thinking basics for Engineers.pdf
CMR University
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Digital water marking system project report
Kamal Acharya
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
MODULE-5 notes [BCG402-CG&V] PART-B.pdf
Alvas Institute of Engineering and technology, Moodabidri
 

YaJug - Cassandra for Java Developers

  • 1. Cassandra for Java Developers DataStax Driver & DevCenter Michaël Figuière Drivers & Developer Tools Architect
  • 2. Client / Server Communication © 2014 DataStax, All Rights Reserved. 2 Client Client Client Client Node Node Replica Replica Replica Node Coordinator node: Forwards all R/W requests to corresponding replicas
  • 3. Request Pipelining © 2014 DataStax, All Rights Reserved. 3 Client Without Request Pipelining Cassandra Client Cassandra With Request Pipelining
  • 4. Notifications © 2014 DataStax, All Rights Reserved. 4 Client Without Notifications With Notifications Node Node Node Client Node Node Node
  • 5. Asynchronous Driver Architecture © 2014 DataStax, All Rights Reserved. 5 Client Thread Node Node Node Client Thread Client Thread Node Driver
  • 6. Asynchronous Driver Architecture © 2014 DataStax, All Rights Reserved. 6 Client Thread Node Node Node Client Thread Client Thread Node 6 2 3 4 5 1 Driver
  • 7. Failover © 2014 DataStax, All Rights Reserved. 7 Client Thread Node Node Node Client Thread Client Thread Node 7 2 4 3 5 1 Driver 6
  • 8. Java Driver Highlights • Reference implementation • Asynchronous architecture based on Netty • Prepared Statements Support • Automatic Failover • Node Discovery • Tunable Load Balancing • Round Robin, Latency Awareness, Multi Data Centers, Replica Awareness • Cassandra Tracing Support • Compression & SSL © 2014 DataStax, All Rights Reserved. 8
  • 9. DataCenter Aware Balancing © 2014 DataStax, All Rights Reserved. 9 Node Node Client Node Node Datacenter B Node Node Client Client Client Client Client Datacenter A Local nodes are queried first, if non are available, the request could be sent to a remote node.
  • 10. Token Aware Balancing © 2014 DataStax, All Rights Reserved. Nodes that own a Replica of the PK being read or written by the query will be contacted first. 10 Node Node Replica Node Client Replica Replica Partition Key will be inferred from Prepared Statements metadata
  • 11. DataStax Driver in Practice <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-­‐driver-­‐core</artifactId> <version>2.1.0</version> </dependency> Available in Maven Central. Depends on Netty, Guava, Metrics Supports Apache Cassandra 1.2 to 2.1 © 2014 DataStax, All Rights Reserved. 11
  • 12. Connect and Write Cluster cluster = Cluster.builder() .addContactPoints("10.1.2.5", "cassandra_node3") .build(); Session session = cluster.connect(“my_keyspace"); session.execute( "INSERT INTO user (user_id, name, email) VALUES (12345, 'johndoe', '[email protected]')" ); The rest of the nodes will be discovered by the driver A keyspace is just like a schema in the SQL world © 2014 DataStax, All Rights Reserved. 12
  • 13. Read ResultSet resultSet = session.execute( Session is a thread safe object. A singleton should be instantiated at startup "SELECT * FROM user WHERE user_id IN (1,8,13)" ); List<Row> rows = resultSet.all(); for (Row row : rows) { String userId = row.getString("user_id"); String name = row.getString("name"); String email = row.getString("email"); } Actually ResultSet also implements Iterable<Row> © 2014 DataStax, All Rights Reserved. 13
  • 14. Write with Prepared Statements PreparedStatement objects are also threadsafe, just create a singleton at startup PreparedStatement insertUser = session.prepare( "INSERT INTO user (user_id, name, email) VALUES (?, ?, ?)" ); BoundStatement statement = insertUser .bind(12345, "johndoe", "[email protected]") .setConsistencyLevel(ConsistencyLevel.QUORUM); session.execute(statement); Parameters can be named as well BoundStatement is a stateful, NON threadsafe object Consistency Level can be set for each statement © 2014 DataStax, All Rights Reserved. 14
  • 15. Asynchronous Read ResultSetFuture future = session.executeAsync( "SELECT * FROM user WHERE user_id IN (1,2,3)" ); ResultSet resultSet = future.get(); List<Row> rows = resultSet.all(); for (Row row : rows) { String userId = row.getString("user_id"); String name = row.getString("name"); String email = row.getString("email"); } Will not block. Returns immediately Will block until less all the connections are busy © 2014 DataStax, All Rights Reserved. 15
  • 16. Asynchronous Read with Callbacks ResultSetFuture future = session.executeAsync( "SELECT * FROM user WHERE user_id IN (1,2,3)" ); future.addListener(new Runnable() { public void run() { // Process the results here } }, executor); ResultSetFuture implements Guava’s ListenableFuture executor = Executors .newCachedThreadPool(); executor = MoreExecutors .sameThreadExecutor(); Only if your listener code is trivial and non blocking as it’ll be executed in the IO Thread …Or any thread pool that you prefer © 2014 DataStax, All Rights Reserved. 16
  • 17. Query Builder import static of QueryBuilder is required in order to use the DSL import static com.datastax.driver.core.querybuilder.QueryBuilder.*; Statement selectAll = select().all().from("user").where(eq("user_id", userId)); session.execute(selectAll); Statement insert = insertInto("user") .value("user_id", 2) .value("name", "johndoe") .value("email", "[email protected]"); session.execute(insert); © 2014 DataStax, All Rights Reserved. 17
  • 18. Object Mapper • Avoid boilerplate for common use cases • Map Objects to Statements and ResultSets to Objects • Do NOT hide Cassandra from the developer • No “clever tricks” à la Hibernate • Not JPA compatible, but JPA-ish API © 2014 DataStax, All Rights Reserved. 18
  • 19. Object Mapper in Practice <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-­‐driver-­‐mapping</artifactId> <version>2.1.0</version> </dependency> Additional artifact for object mapping Available from Driver 2.1.0 © 2014 DataStax, All Rights Reserved. 19
  • 20. Basic Object Mapping CREATE TYPE address ( street text, city text, zip int ); CREATE TABLE users ( email text PRIMARY KEY, address address ); @UDT(keyspace = "ks", name = "address") public class Address { private String street; private String city; private int zip; // getters and setters omitted... } @Table(keyspace = "ks", name = "users") public class User { @PartitionKey private String email; private Address address; // getters and setters omitted... } © 2014 DataStax, All Rights Reserved. 20
  • 21. Basic Object Mapping MappingManager manager = new MappingManager(session); Mapper mapper = manager.mapper(User.class); UserProfile myProfile = mapper.get("[email protected]"); ListenableFuture saveFuture = mapper.saveAsync(anotherProfile); mapper.delete("[email protected]"); Mapper, just like Session, is a thread-safe object. Create a singleton at startup. get() returns a mapped row for the given Primary Key ListenableFuture from Guava. Completed when the write is acknowledged. © 2014 DataStax, All Rights Reserved. 21
  • 22. Accessors @Accessor interface UserAccessor { @Query("SELECT * FROM user_profiles LIMIT :max") Result<User> firstN(@Param("max") int limit); } UserAccessor accessor = manager.createAccessor(UserAccessor.class); Result<User> users = accessor.firstN(10); for (User user : users) { System.out.println( profile.getAddress().getZip() ); } Result is like ResultSet but specialized for a mapped class… …so we iterate over it just like we would with a ResultSet © 2014 DataStax, All Rights Reserved. 22
  • 24. We’re Hiring! github.com/datastax blog.datastax.com @mfiguiere …seriously I really mean it, so if you’re passionated about beautiful technology feel free to talk to me! Work remotely from anywhere in Europe, even Luxembourg…