kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | fb3eea0b45a26d25db044e6b6a3ddfe2181fce9faaaba4e52808f19c14326f6c |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-01-08 15:24 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-01-11 17:35 +01:00 |
| Parents | 23b289c30570 |
40 files changed
modified README.md +5 −5
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | [e.g. |
| 11 | 11 | 2.1.9](https://github.com/datastax/java-driver/tree/2.1.9).* |
| 12 | 12 | |
| 13 | -A modern, [feature-rich](features/) and highly tunable Java client | |
| 13 | +A modern, [feature-rich](manual/) and highly tunable Java client | |
| 14 | 14 | library for Apache Cassandra (1.2+) and DataStax Enterprise (3.1+) using |
| 15 | 15 | exclusively Cassandra's binary protocol and Cassandra Query Language v3. |
| 16 | 16 | |
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | [simple_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html |
| 34 | 34 | [prepared_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#prepare(com.datastax.driver.core.RegularStatement) |
| 35 | 35 | [batch_st]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html |
| 36 | -[pool]: features/pooling/ | |
| 36 | +[pool]: manual/pooling/ | |
| 37 | 37 | [lbp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html |
| 38 | 38 | [retry_policy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html |
| 39 | 39 | [query_builder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html |
| @@ -62,7 +62,7 @@ | ||
| 62 | 62 | other drivers, Cassandra, and DSE. |
| 63 | 63 | - DOCS: the [user guide](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html) |
| 64 | 64 | has introductory material. We are progressively migrating the doc |
| 65 | - [here](features/) with more technical details. | |
| 65 | + [here](manual/) with more technical details. | |
| 66 | 66 | - API: http://www.datastax.com/drivers/java/2.1 |
| 67 | 67 | |
| 68 | 68 | **Feeback requested:** help us focus our efforts, provide your input on the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short). |
| @@ -91,7 +91,7 @@ | ||
| 91 | 91 | </dependency> |
| 92 | 92 | ``` |
| 93 | 93 | |
| 94 | -We also provide a [shaded JAR](features/shaded_jar/) | |
| 94 | +We also provide a [shaded JAR](manual/shaded_jar/) | |
| 95 | 95 | to avoid the explicit dependency to Netty. |
| 96 | 96 | |
| 97 | 97 | If you can't use a dependency management tool, a |
| @@ -101,7 +101,7 @@ | ||
| 101 | 101 | ## Compatibility |
| 102 | 102 | |
| 103 | 103 | The Java client driver 2.1 ([branch 2.1](https://github.com/datastax/java-driver/tree/2.1)) is compatible with Apache |
| 104 | -Cassandra 1.2, 2.0, 2.1 and 2.2 (see [this page](http://datastax.github.io/java-driver/features/native_protocol) for | |
| 104 | +Cassandra 1.2, 2.0, 2.1 and 2.2 (see [this page](http://datastax.github.io/java-driver/manual/native_protocol) for | |
| 105 | 105 | the most up-to-date compatibility information). |
| 106 | 106 | |
| 107 | 107 | UDT and tuple support is available only when using Apache Cassandra 2.1 or higher (see [CQL improvements in Cassandra 2.1](http://www.datastax.com/dev/blog/cql-in-2-1)). |
modified docs.yaml +8 −0
| @@ -5,6 +5,14 @@ | ||
| 5 | 5 | homepage: http://datastax.github.io/java-driver/ |
| 6 | 6 | theme: datastax |
| 7 | 7 | sections: |
| 8 | + - title: Manual | |
| 9 | + prefix: /manual | |
| 10 | + sources: | |
| 11 | + - type: markdown | |
| 12 | + files: 'manual/**/*.md' | |
| 13 | + # The 'manual' section was called 'features' in older releases. Leave both | |
| 14 | + # definitions and Documentor will pick up whichever exists and ignore the | |
| 15 | + # other. | |
| 8 | 16 | - title: Features |
| 9 | 17 | prefix: /features |
| 10 | 18 | sources: |
modified faq/README.md +2 −2
| @@ -2,10 +2,10 @@ | ||
| 2 | 2 | |
| 3 | 3 | ### How do I implement paging? |
| 4 | 4 | |
| 5 | -When using [native protocol](../features/native_protocol/) version 2 or | |
| 5 | +When using [native protocol](../manual/native_protocol/) version 2 or | |
| 6 | 6 | higher, the driver automatically pages large result sets under the hood. |
| 7 | 7 | You can also save the paging state to resume iteration later. See [this |
| 8 | -page](../features/paging/) for more information. | |
| 8 | +page](../manual/paging/) for more information. | |
| 9 | 9 | |
| 10 | 10 | Native protocol v1 does not support paging, but you can emulate it in |
| 11 | 11 | CQL with `LIMIT` and the `token()` function. See |
deleted features/README.md +0 −17
| @@ -1,17 +0,0 @@ | ||
| 1 | -## Features | |
| 2 | - | |
| 3 | -This part of the documentation is organized into sub-sections covering | |
| 4 | -specific topics. | |
| 5 | - | |
| 6 | -If you're reading this from the [generated HTML documentation on | |
| 7 | -github.io](http://datastax.github.io/java-driver/), use the "Read More" | |
| 8 | -menu on the right hand side. If you're [browsing the source files on | |
| 9 | -github.com](https://github.com/datastax/java-driver/tree/2.1/features), | |
| 10 | -simply navigate to each sub-directory. | |
| 11 | - | |
| 12 | -This is a work in progress: new sections will be added to cover existing | |
| 13 | -features or document new ones. | |
| 14 | - | |
| 15 | -You can also find more help in the legacy | |
| 16 | -[user documentation](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html) | |
| 17 | -on the DataStax website. |
deleted features/address_resolution/README.md +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -## Address resolution | |
| 2 | - | |
| 3 | -The driver auto-detects new Cassandra nodes added to the cluster through server | |
| 4 | -side push notifications and through checking the system tables. | |
| 5 | - | |
| 6 | -For each node, the address the driver will receive will correspond to the address set as | |
| 7 | -`rpc_address` in the node's `cassandra.yaml` file. In most cases, this is the correct value. | |
| 8 | -However, sometimes the addresses received through this mechanism will either not be | |
| 9 | -reachable directly by the driver, or should not be the preferred address to use | |
| 10 | -(for instance, it might be a private IP, but some clients may have to use a public IP, or | |
| 11 | -go through a router). | |
| 12 | - | |
| 13 | -### The [AddressTranslater][at] interface | |
| 14 | - | |
| 15 | -This interface allows you to deal with such cases, by transforming the address sent by a | |
| 16 | -Cassandra node to another address to be used by the driver for connection. | |
| 17 | - | |
| 18 | -```java | |
| 19 | -public class MyAddressTranslater implements AddressTranslater { | |
| 20 | - public InetSocketAddress translate(InetSocketAddress address) { | |
| 21 | - ... // your custom translation logic | |
| 22 | - } | |
| 23 | -} | |
| 24 | - | |
| 25 | -Cluster cluster = Cluster.builder() | |
| 26 | - .addContactPoint("1.2.3.4") | |
| 27 | - .withAddressTranslater(new MyAddressTranslater()) | |
| 28 | - .build(); | |
| 29 | -``` | |
| 30 | - | |
| 31 | -Notes: | |
| 32 | - | |
| 33 | -* the contact points provided while creating the `Cluster` are not translated, only addresses | |
| 34 | - retrieved from or sent by Cassandra nodes are; | |
| 35 | -* you might want to implement [CloseableAddressTranslater][cat] if your | |
| 36 | - implementation has state that should be cleaned up when the `Cluster` | |
| 37 | - shuts down. This is provided as a separate interface for historical | |
| 38 | - reasons, the `close()` method will be merged in `AddressTranslater` in a | |
| 39 | - future release. | |
| 40 | - | |
| 41 | -[at]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/AddressTranslater.html | |
| 42 | -[cat]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/CloseableAddressTranslater.html | |
| 43 | - | |
| 44 | -### EC2 multi-region | |
| 45 | - | |
| 46 | -[EC2MultiRegionAddressTranslater][ec2] is provided out of the box. It | |
| 47 | -helps optimize network costs when your infrastructure (both Cassandra | |
| 48 | -nodes *and* clients) is distributed across multiple Amazon EC2 regions: | |
| 49 | - | |
| 50 | -* a client communicating with a Cassandra node *in the same EC2 region* should use the node's | |
| 51 | - private IP (which is less expensive); | |
| 52 | -* a client communicating with a node in a different region should use the public IP. | |
| 53 | - | |
| 54 | -To use this implementation, provide an instance when initializing the `Cluster`: | |
| 55 | - | |
| 56 | -```java | |
| 57 | -Cluster cluster = Cluster.builder() | |
| 58 | - .addContactPoint("1.2.3.4") | |
| 59 | - .withAddressTranslater(new EC2MultiRegionAddressTranslater()) | |
| 60 | - .build(); | |
| 61 | -``` | |
| 62 | - | |
| 63 | -This class performs a reverse DNS lookup of the origin address, to find the domain name of the | |
| 64 | -target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the | |
| 65 | -private/public switch automatically based on location. | |
| 66 | - | |
| 67 | -[ec2]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.html |
deleted features/async/README.md +0 −162
| @@ -1,162 +0,0 @@ | ||
| 1 | -## Asynchronous programming | |
| 2 | - | |
| 3 | -The driver exposes an asynchronous API that allows you to write programs | |
| 4 | -in a fully-non blocking manner. Asynchronous methods return instances of | |
| 5 | -Guava's [ListenableFuture], that can be conveniently chained and | |
| 6 | -composed. | |
| 7 | - | |
| 8 | -Here is a short example that opens a session and runs a query | |
| 9 | -asynchronously: | |
| 10 | - | |
| 11 | -```java | |
| 12 | -import com.google.common.util.concurrent.*; | |
| 13 | - | |
| 14 | -ListenableFuture<Session> session = cluster.connectAsync(); | |
| 15 | - | |
| 16 | -// Use transform with an AsyncFunction to chain an async operation after another: | |
| 17 | -ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 18 | - new AsyncFunction<Session, ResultSet>() { | |
| 19 | - public ListenableFuture<ResultSet> apply(Session session) throws Exception { | |
| 20 | - return session.executeAsync("select release_version from system.local"); | |
| 21 | - } | |
| 22 | - }); | |
| 23 | - | |
| 24 | -// Use transform with a simple Function to apply a synchronous computation on the result: | |
| 25 | -ListenableFuture<String> version = Futures.transform(resultSet, | |
| 26 | - new Function<ResultSet, String>() { | |
| 27 | - public String apply(ResultSet rs) { | |
| 28 | - return rs.one().getString("release_version"); | |
| 29 | - } | |
| 30 | - }); | |
| 31 | - | |
| 32 | -// Use a callback to perform an action once the future is complete: | |
| 33 | -Futures.addCallback(version, new FutureCallback<String>() { | |
| 34 | - public void onSuccess(String version) { | |
| 35 | - System.out.printf("Cassandra version: %s%n", version); | |
| 36 | - } | |
| 37 | - | |
| 38 | - public void onFailure(Throwable t) { | |
| 39 | - System.out.printf("Failed to retrieve the version: %s%n", | |
| 40 | - t.getMessage()); | |
| 41 | - } | |
| 42 | -}); | |
| 43 | -``` | |
| 44 | - | |
| 45 | -### Async paging | |
| 46 | - | |
| 47 | -If you consume a `ResultSet` in a callback, be aware that iterating the | |
| 48 | -rows will trigger synchronous queries as you page through the results. | |
| 49 | -To avoid this, use [getAvailableWithoutFetching] to limit the iteration | |
| 50 | -to the current page, and [fetchMoreResults] to get a future to the next | |
| 51 | -page (see also the section on [paging](../paging/)). | |
| 52 | -Here is a full example: | |
| 53 | - | |
| 54 | -[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching-- | |
| 55 | -[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#fetchMoreResults-- | |
| 56 | - | |
| 57 | -```java | |
| 58 | -Statement statement = new SimpleStatement("select * from foo").setFetchSize(20); | |
| 59 | -ListenableFuture<Void> future = Futures.transform( | |
| 60 | - session.executeAsync(statement), | |
| 61 | - iterateFirst()); | |
| 62 | - | |
| 63 | -// Unfortunately we have to special-case for the first page because the signatures of the | |
| 64 | -// futures differ. | |
| 65 | -// In 3.0, fetchMoreResults() will return a Future<ResultSet> to avoid this. | |
| 66 | -private static AsyncFunction<ResultSet, Void> iterateFirst() { | |
| 67 | - return new AsyncFunction<ResultSet, Void>() { | |
| 68 | - @Override | |
| 69 | - public ListenableFuture<Void> apply(ResultSet rs) throws Exception { | |
| 70 | - return iterate(rs, 1).apply(null); | |
| 71 | - } | |
| 72 | - }; | |
| 73 | -} | |
| 74 | - | |
| 75 | -private static AsyncFunction<Void, Void> iterate(final ResultSet rs, final int page) { | |
| 76 | - return new AsyncFunction<Void, Void>() { | |
| 77 | - @Override | |
| 78 | - public ListenableFuture<Void> apply(Void v) throws Exception { | |
| 79 | - | |
| 80 | - // How far we can go without triggering the blocking fetch: | |
| 81 | - int remainingInPage = rs.getAvailableWithoutFetching(); | |
| 82 | - | |
| 83 | - System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage); | |
| 84 | - | |
| 85 | - for (Row row : rs) { | |
| 86 | - System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row); | |
| 87 | - if (--remainingInPage == 0) | |
| 88 | - break; | |
| 89 | - } | |
| 90 | - System.out.printf("Done page %d%n", page); | |
| 91 | - | |
| 92 | - boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null; | |
| 93 | - if (wasLastPage) { | |
| 94 | - System.out.println("Done iterating"); | |
| 95 | - return Futures.immediateFuture(null); | |
| 96 | - } else { | |
| 97 | - ListenableFuture<Void> future = rs.fetchMoreResults(); | |
| 98 | - return Futures.transform(future, iterate(rs, page + 1)); | |
| 99 | - } | |
| 100 | - } | |
| 101 | - }; | |
| 102 | -} | |
| 103 | -``` | |
| 104 | - | |
| 105 | -### Good practices | |
| 106 | - | |
| 107 | -If your callback is slow, consider providing a separate executor. | |
| 108 | -Otherwise the callback might run on one of the driver's I/O threads, | |
| 109 | -blocking I/O operations for other requests while it is running: | |
| 110 | - | |
| 111 | -```java | |
| 112 | -ListenableFuture<String> result = Futures.transform(resultSet, | |
| 113 | - new Function<ResultSet, String>() { | |
| 114 | - public String apply(ResultSet rs) { | |
| 115 | - return someVeryLongComputation(rs); | |
| 116 | - } | |
| 117 | - }, myCustomExecutor); | |
| 118 | -``` | |
| 119 | - | |
| 120 | -Avoid blocking operations in callbacks, especially if you don't provide | |
| 121 | -a separate executor. This could easily lead to deadlock if the thread | |
| 122 | -that's supposed to complete the blocking call is also the thread that's | |
| 123 | -waiting on it: | |
| 124 | - | |
| 125 | -```java | |
| 126 | -ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 127 | - new Function<Session, ResultSet>() { | |
| 128 | - public ResultSet apply(Session session) { | |
| 129 | - // Synchronous operation in a callback. | |
| 130 | - // DON'T DO THIS! It might deadlock. | |
| 131 | - return session.execute("select release_version from system.local"); | |
| 132 | - } | |
| 133 | - }); | |
| 134 | -``` | |
| 135 | - | |
| 136 | -### Known limitations | |
| 137 | - | |
| 138 | -There are still a few places where the driver will block internally | |
| 139 | -(mainly for historical reasons): | |
| 140 | - | |
| 141 | -* [Cluster#init][init] performs blocking I/O operations. To avoid | |
| 142 | - issues, you should create your `Cluster` instances while bootstrapping | |
| 143 | - your application, and call `init` immediately. If you need to create new | |
| 144 | - instances at runtime, make sure this does not happen on an I/O thread. | |
| 145 | -* if a connection pool is busy, the driver will block until a connection | |
| 146 | - becomes available. To avoid this, set | |
| 147 | - [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the | |
| 148 | - driver will not block, just move to the next host immediately. | |
| 149 | -* if the session is set to a specific keyspace (either at startup or by | |
| 150 | - issuing a `USE` statement on a running session), the keyspace needs to | |
| 151 | - be propagated to any newly created connection. This is done when the | |
| 152 | - connection is first borrowed from the connection pool, and currently | |
| 153 | - blocks. To avoid any issue, only use a session with no keyspace set | |
| 154 | - (i.e. created by `Cluster#connect()`). This will be addressed in | |
| 155 | - [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893). | |
| 156 | -* trying to read fields from a [query trace] will block if the trace | |
| 157 | - hasn't been fetched already. | |
| 158 | - | |
| 159 | -[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained | |
| 160 | -[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init() | |
| 161 | -[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 162 | -[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html |
deleted features/compression/README.md +0 −88
| @@ -1,88 +0,0 @@ | ||
| 1 | -## Compression | |
| 2 | - | |
| 3 | -Cassandra's binary protocol supports optional compression of | |
| 4 | -transport-level requests and responses, for example: | |
| 5 | - | |
| 6 | -* a query with its serialized parameters; | |
| 7 | -* a [page](../paging/) from a result set, i.e. a list of serialized | |
| 8 | - rows. | |
| 9 | - | |
| 10 | -It reduces network traffic at the cost of CPU overhead, therefore it | |
| 11 | -will likely be beneficial when you have larger payloads. | |
| 12 | - | |
| 13 | -Two algorithms are available: | |
| 14 | -[LZ4](https://github.com/jpountz/lz4-java) and | |
| 15 | -[Snappy](https://code.google.com/p/snappy/). | |
| 16 | -Both rely on third-party libraries, declared by the driver as *optional* | |
| 17 | -dependencies. So If you use a build tool like Maven, you'll need to | |
| 18 | -declare an explicit dependency to pull the appropriate library in your | |
| 19 | -application's classpath. Then you configure compression at driver | |
| 20 | -startup. | |
| 21 | - | |
| 22 | -### LZ4 | |
| 23 | - | |
| 24 | -Maven dependency: | |
| 25 | - | |
| 26 | -```xml | |
| 27 | -<dependency> | |
| 28 | - <groupId>net.jpountz.lz4</groupId> | |
| 29 | - <artifactId>lz4</artifactId> | |
| 30 | - <version>1.2.0</version> | |
| 31 | -</dependency> | |
| 32 | -``` | |
| 33 | - | |
| 34 | -Always check the exact version of the library: go to the driver's | |
| 35 | -[parent POM][pom] (change the URL to match your driver version) and look | |
| 36 | -for the `lz4.version` property. | |
| 37 | - | |
| 38 | -Driver configuration: | |
| 39 | - | |
| 40 | -```java | |
| 41 | -cluster = Cluster.builder() | |
| 42 | - .addContactPoint("127.0.0.1") | |
| 43 | - .withCompression(ProtocolOptions.Compression.LZ4) | |
| 44 | - .build(); | |
| 45 | -``` | |
| 46 | - | |
| 47 | -LZ4-java has three internal implementations (from fastest to slowest): | |
| 48 | - | |
| 49 | -* JNI; | |
| 50 | -* pure Java using sun.misc.Unsafe; | |
| 51 | -* pure Java using only "safe" classes. | |
| 52 | - | |
| 53 | -It will pick the best implementation depending on what's possible on | |
| 54 | -your platform. To find out which one was chosen, [enable INFO | |
| 55 | -logs](../logging/) on the category | |
| 56 | -`com.datastax.driver.core.FrameCompressor` and look for a log similar to | |
| 57 | -this: | |
| 58 | - | |
| 59 | -``` | |
| 60 | -INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI | |
| 61 | -``` | |
| 62 | - | |
| 63 | -### Snappy | |
| 64 | - | |
| 65 | -Maven dependency: | |
| 66 | - | |
| 67 | -```xml | |
| 68 | -<dependency> | |
| 69 | - <groupId>org.xerial.snappy</groupId> | |
| 70 | - <artifactId>snappy-java</artifactId> | |
| 71 | - <version>1.0.5</version> | |
| 72 | -</dependency> | |
| 73 | -``` | |
| 74 | - | |
| 75 | -Always check the exact version of the library: go to the driver's | |
| 76 | -[parent POM][pom] (change the URL to match your driver version) and look | |
| 77 | -for the `snappy.version` property. | |
| 78 | - | |
| 79 | -Driver configuration: | |
| 80 | - | |
| 81 | -```java | |
| 82 | -cluster = Cluster.builder() | |
| 83 | - .addContactPoint("127.0.0.1") | |
| 84 | - .withCompression(ProtocolOptions.Compression.SNAPPY) | |
| 85 | - .build(); | |
| 86 | -``` | |
| 87 | - | |
| 88 | -[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/2.1.9/cassandra-driver-parent-2.1.9.pom |
deleted features/logging/README.md +0 −303
| @@ -1,303 +0,0 @@ | ||
| 1 | -## Logging | |
| 2 | - | |
| 3 | -### Setup | |
| 4 | - | |
| 5 | -DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages; | |
| 6 | -SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete | |
| 7 | -implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend. | |
| 8 | - | |
| 9 | -The driver itself does not attempt to configure any concrete logging framework. | |
| 10 | -It is up to client applications using the driver to correctly set up their classpath and | |
| 11 | -runtime configuration to be able to capture log messages emitted by the driver. | |
| 12 | -Concretely, client applications need to provide, at runtime, a *binding* to any logging framework | |
| 13 | -of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping). | |
| 14 | - | |
| 15 | -If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file. | |
| 16 | -For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency: | |
| 17 | - | |
| 18 | -```xml | |
| 19 | -<dependency> | |
| 20 | - <groupId>ch.qos.logback</groupId> | |
| 21 | - <artifactId>logback-classic</artifactId> | |
| 22 | - <version>1.1.3</version> | |
| 23 | -</dependency> | |
| 24 | -``` | |
| 25 | - | |
| 26 | -If you are using Log4J 1.2 instead, add the following dependency: | |
| 27 | - | |
| 28 | -```xml | |
| 29 | -<dependency> | |
| 30 | - <groupId>org.slf4j</groupId> | |
| 31 | - <artifactId>slf4j-log4j12</artifactId> | |
| 32 | - <version>1.7.12</version> | |
| 33 | -</dependency> | |
| 34 | -``` | |
| 35 | - | |
| 36 | -Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for | |
| 37 | -other logging frameworks, and for troubleshooting dependency resolution problems. | |
| 38 | - | |
| 39 | -### Configuration | |
| 40 | - | |
| 41 | -Each logging framework has its own configuration rules, but all of them provide | |
| 42 | -different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories* | |
| 43 | -(messages from different categories or loggers can be filtered out separately or printed out | |
| 44 | -differently), and different *appenders* (message receptacles such as the standard console, | |
| 45 | -the error console, a file on disk, a socket...). | |
| 46 | - | |
| 47 | -Check your logging framework documentation for more information about how to properly configure it. | |
| 48 | -You can also find some configuration examples below. | |
| 49 | - | |
| 50 | -### Useful loggers | |
| 51 | - | |
| 52 | -When debugging the Java driver, the following loggers could be particularly useful | |
| 53 | -and provide hints about what's going wrong. | |
| 54 | - | |
| 55 | -* `com.datastax.driver.core.Cluster` | |
| 56 | - * ERROR | |
| 57 | - * Authentication errors | |
| 58 | - * Unexpected errors when handling events, reconnecting, refreshing schemas | |
| 59 | - * Unexpected events | |
| 60 | - * WARN | |
| 61 | - * Cluster name mismatches | |
| 62 | - * Unreachable contact points | |
| 63 | - * Unsupported protocol versions | |
| 64 | - * Schema disagreements | |
| 65 | - * Ignored notifications due to high contention | |
| 66 | - * INFO | |
| 67 | - * Hosts added or removed | |
| 68 | - * DEBUG | |
| 69 | - * Cluster lifecycle (start, shutdown) | |
| 70 | - * Event delivery notifications (schema changes, topology changes) | |
| 71 | - * Topology change events: hosts Up / Down / Added / Removed | |
| 72 | - * Hosts being ignored | |
| 73 | - * Protocol version negotiation | |
| 74 | - * Reconnection attempts | |
| 75 | - * Schema metadata refreshes | |
| 76 | - * TRACE | |
| 77 | - * Connection pools lifecycle (create, renew, refresh) | |
| 78 | -* `com.datastax.driver.core.Session` | |
| 79 | - * ERROR | |
| 80 | - * Errors related to connection pools | |
| 81 | - * WARN | |
| 82 | - * Problems related to connection pools | |
| 83 | - * DEBUG | |
| 84 | - * Connection pools lifecycle (create, renew, refresh) | |
| 85 | -* `com.datastax.driver.core.RequestHandler` | |
| 86 | - * ERROR | |
| 87 | - * Unexpected errors preparing queries | |
| 88 | - * Queries sent to a bootstrapping host | |
| 89 | - * Unexpected server errors | |
| 90 | - * WARN | |
| 91 | - * Queries sent to an overloaded host | |
| 92 | - * INFO | |
| 93 | - * Unprepared queries | |
| 94 | - * DEBUG | |
| 95 | - * Retry attempts | |
| 96 | - * TRACE | |
| 97 | - * Host currently being queried | |
| 98 | -* `com.datastax.driver.core.Connection` | |
| 99 | - * WARN | |
| 100 | - * Problem setting keyspace | |
| 101 | - * Errors closing Netty channel | |
| 102 | - * DEBUG | |
| 103 | - * Connection lifecycle (open, close, defunct) | |
| 104 | - * Error connecting or writing requests | |
| 105 | - * Heartbeats | |
| 106 | - * TRACE | |
| 107 | - * Authentication progress | |
| 108 | - * Sending requests | |
| 109 | - * Receiving responses | |
| 110 | - | |
| 111 | -### Logging query latencies | |
| 112 | - | |
| 113 | -The `QueryLogger` provides clients with the ability to log queries | |
| 114 | -executed by the driver, and especially, it allows client to track slow | |
| 115 | -queries, i.e. queries that take longer to complete than a configured | |
| 116 | -threshold in milliseconds. | |
| 117 | - | |
| 118 | -To turn on this feature, you first need to instantiate and register a `QueryLogger` instance: | |
| 119 | - | |
| 120 | -```java | |
| 121 | -Cluster cluster = ... | |
| 122 | -QueryLogger queryLogger = QueryLogger.builder(cluster) | |
| 123 | - .withConstantThreshold(...) | |
| 124 | - .withMaxQueryStringLength(...) | |
| 125 | -.build(); | |
| 126 | -cluster.register(queryLogger); | |
| 127 | -``` | |
| 128 | - | |
| 129 | -Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide. | |
| 130 | -Besides, you can adjust several parameters such as the maximum query string length to be printed, | |
| 131 | -the maximum number of parameters to print, etc. Refer to the | |
| 132 | -`QueryLogger` [API docs][query_logger] for more information. | |
| 133 | - | |
| 134 | -Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger` | |
| 135 | -uses 3 different loggers: | |
| 136 | - | |
| 137 | -* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds. | |
| 138 | -* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete. | |
| 139 | -* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception. | |
| 140 | - | |
| 141 | -You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries | |
| 142 | -that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above), | |
| 143 | -then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J: | |
| 144 | - | |
| 145 | -```xml | |
| 146 | - <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 147 | - <level value="DEBUG"/> | |
| 148 | - </logger> | |
| 149 | -``` | |
| 150 | - | |
| 151 | -The `QueryLogger` would then print messages such as this for every slow query: | |
| 152 | - | |
| 153 | -``` | |
| 154 | -DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?; | |
| 155 | -``` | |
| 156 | - | |
| 157 | -As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger | |
| 158 | -to TRACE instead, e.g. with Log4J: | |
| 159 | - | |
| 160 | -```xml | |
| 161 | - <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 162 | - <level value="TRACE"/> | |
| 163 | - </logger> | |
| 164 | -``` | |
| 165 | - | |
| 166 | -The `QueryLogger` would then print messages such as this for every slow query: | |
| 167 | - | |
| 168 | -``` | |
| 169 | -TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42]; | |
| 170 | -``` | |
| 171 | - | |
| 172 | -Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters. | |
| 173 | -See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary. | |
| 174 | - | |
| 175 | -#### Constant vs Dynamic thresholds | |
| 176 | - | |
| 177 | -Currently the `QueryLogger` can be configured to track slow queries using either | |
| 178 | -a constant threshold in milliseconds (which is the default behavior), or | |
| 179 | -a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`. | |
| 180 | - | |
| 181 | -**Dynamic thresholds are still a beta feature as of version 2.1.6: they | |
| 182 | -haven't been extensively tested yet, and the API is still subject to | |
| 183 | -change.** | |
| 184 | - | |
| 185 | -Refer to the `QueryLogger` [API docs][query_logger] for an example of usage. | |
| 186 | - | |
| 187 | -### Performance Tips | |
| 188 | - | |
| 189 | -* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html) | |
| 190 | -and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders | |
| 191 | -that can significantly boost latencies when writing log messages. | |
| 192 | -* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration | |
| 193 | -without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html); | |
| 194 | -Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)). | |
| 195 | - | |
| 196 | -### Logback Example | |
| 197 | - | |
| 198 | -Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!* | |
| 199 | - | |
| 200 | -It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file. | |
| 201 | -By default, only messages with ERROR level or higher are logged. | |
| 202 | - | |
| 203 | -It also turns on slow query tracing as described above. | |
| 204 | - | |
| 205 | -```xml | |
| 206 | -<?xml version="1.0" encoding="UTF-8"?> | |
| 207 | -<configuration> | |
| 208 | - | |
| 209 | - <!-- log INFO or higher messages to the console --> | |
| 210 | - <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> | |
| 211 | - <encoder> | |
| 212 | - <pattern>%-5p %msg%n</pattern> | |
| 213 | - </encoder> | |
| 214 | - </appender> | |
| 215 | - | |
| 216 | - <!-- log everything to a rolling file --> | |
| 217 | - <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender"> | |
| 218 | - <file>driver.log</file> | |
| 219 | - <encoder> | |
| 220 | - <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern> | |
| 221 | - </encoder> | |
| 222 | - <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> | |
| 223 | - <!-- daily rollover --> | |
| 224 | - <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern> | |
| 225 | - <!-- keep 30 days' worth of history --> | |
| 226 | - <maxHistory>30</maxHistory> | |
| 227 | - </rollingPolicy> | |
| 228 | - </appender> | |
| 229 | - | |
| 230 | - <!-- use AsyncAppender for lower latencies --> | |
| 231 | - <appender name="async" class="ch.qos.logback.classic.AsyncAppender"> | |
| 232 | - <appender-ref ref="console" /> | |
| 233 | - <appender-ref ref="file" /> | |
| 234 | - </appender> | |
| 235 | - | |
| 236 | - <!-- | |
| 237 | - Turn on slow query logging by setting this logger to DEBUG; | |
| 238 | - set level to TRACE to also log query parameters | |
| 239 | - --> | |
| 240 | - <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" /> | |
| 241 | - | |
| 242 | - <root level="ERROR"> | |
| 243 | - <appender-ref ref="async" /> | |
| 244 | - </root> | |
| 245 | - | |
| 246 | -</configuration> | |
| 247 | -``` | |
| 248 | - | |
| 249 | -### Log4J Example | |
| 250 | - | |
| 251 | -Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!* | |
| 252 | - | |
| 253 | -It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file. | |
| 254 | -By default, only messages with ERROR level or higher are logged. | |
| 255 | - | |
| 256 | -It also turns on slow query tracing as described above. | |
| 257 | - | |
| 258 | -```xml | |
| 259 | -<log4j:configuration> | |
| 260 | - | |
| 261 | - <!-- log INFO or higher messages to the console --> | |
| 262 | - <appender name="console" class="org.apache.log4j.ConsoleAppender"> | |
| 263 | - <param name="threshold" value="INFO"/> | |
| 264 | - <layout class="org.apache.log4j.PatternLayout"> | |
| 265 | - <param name="ConversionPattern" value="%-5p %m%n"/> | |
| 266 | - </layout> | |
| 267 | - </appender> | |
| 268 | - | |
| 269 | - <!-- log everything to a rolling file --> | |
| 270 | - <appender name="file" class="org.apache.log4j.RollingFileAppender"> | |
| 271 | - <param name="file" value="driver.log"/> | |
| 272 | - <param name="append" value="false"/> | |
| 273 | - <param name="maxFileSize" value="1GB"/> | |
| 274 | - <param name="maxBackupIndex" value="10"/> | |
| 275 | - <layout class="org.apache.log4j.PatternLayout"> | |
| 276 | - <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/> | |
| 277 | - </layout> | |
| 278 | - </appender> | |
| 279 | - | |
| 280 | - <!-- use AsyncAppender for lower latencies --> | |
| 281 | - <appender name="async" class="org.apache.log4j.AsyncAppender"> | |
| 282 | - <param name="BufferSize" value="500"/> | |
| 283 | - <appender-ref ref="file"/> | |
| 284 | - <appender-ref ref="console"/> | |
| 285 | - </appender> | |
| 286 | - | |
| 287 | - <!-- | |
| 288 | - Turn on slow query logging by setting this logger to DEBUG; | |
| 289 | - set level to TRACE to also log query parameters | |
| 290 | - --> | |
| 291 | - <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 292 | - <level value="DEBUG"/> | |
| 293 | - </logger> | |
| 294 | - | |
| 295 | - <root> | |
| 296 | - <priority value="ERROR"/> | |
| 297 | - <appender-ref ref="async"/> | |
| 298 | - </root> | |
| 299 | - | |
| 300 | -</log4j:configuration> | |
| 301 | -``` | |
| 302 | - | |
| 303 | -[query_logger]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryLogger.html |
deleted features/metadata/README.md +0 −194
| @@ -1,194 +0,0 @@ | ||
| 1 | -## Metadata | |
| 2 | - | |
| 3 | -The driver maintains global information about the Cassandra cluster it | |
| 4 | -is connected to. It is available via | |
| 5 | -[Cluster#getMetadata()][getMetadata]. | |
| 6 | - | |
| 7 | -[getMetadata]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#getMetadata() | |
| 8 | - | |
| 9 | -### Schema metadata | |
| 10 | - | |
| 11 | -Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces] | |
| 12 | -to get keyspace-level metadata. From there you can access the keyspace's | |
| 13 | -objects (tables, and UDTs and UDFs if relevant). | |
| 14 | - | |
| 15 | -[getKeyspace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String) | |
| 16 | -[getKeyspaces]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getKeyspaces() | |
| 17 | - | |
| 18 | -#### Refreshes | |
| 19 | - | |
| 20 | -Schema metadata gets refreshed in the following circumstances: | |
| 21 | - | |
| 22 | -* **schema changes via the driver**: after successfully executing a | |
| 23 | - schema-altering query (ex: `CREATE TABLE`), the driver waits for | |
| 24 | - schema agreement (see below), then refreshes the schema. | |
| 25 | -* **third-party schema changes**: if another client (cqlsh, other driver | |
| 26 | - instance...) changes the schema, the driver gets notified by Cassandra | |
| 27 | - via a push notification. It refreshes the schema directly (there is no | |
| 28 | - need to wait for schema agreement since Cassandra has already done it). | |
| 29 | - | |
| 30 | -#### Subscribing to schema changes | |
| 31 | - | |
| 32 | -Users interested in being notified of schema changes can implement the | |
| 33 | -[SchemaChangeListener][SchemaChangeListener] interface. | |
| 34 | - | |
| 35 | -Every listener must [be registered][registerListener] against a `Cluster` instance: | |
| 36 | - | |
| 37 | -```java | |
| 38 | -Cluster cluster = ... | |
| 39 | -SchemaChangeListener myListener = ... | |
| 40 | -cluster.register(myListener); | |
| 41 | -``` | |
| 42 | - | |
| 43 | -Once registered, the listener will be notified of all schema changes detected by the driver, | |
| 44 | -regardless of where they originate from. | |
| 45 | - | |
| 46 | -Note that it is preferable to register a listener only *after* the cluster is fully initialized, | |
| 47 | -otherwise the listener could be notified with a great deal of "Added" events as | |
| 48 | -the driver builds the schema metadata from scratch for the first time. | |
| 49 | - | |
| 50 | -[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SchemaChangeListener.html | |
| 51 | -[registerListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener) | |
| 52 | - | |
| 53 | -#### Schema agreement | |
| 54 | - | |
| 55 | -Schema changes need to be propagated to all nodes in the cluster. Once | |
| 56 | -they have settled on a common version, we say that they are in | |
| 57 | -agreement. | |
| 58 | - | |
| 59 | -As explained above, the driver waits for schema agreement after | |
| 60 | -executing a schema-altering query. This is to ensure that subsequent | |
| 61 | -requests (which might get routed to different nodes) see an up-to-date | |
| 62 | -version of the schema. | |
| 63 | - | |
| 64 | -```ditaa | |
| 65 | - Application Driver Cassandra | |
| 66 | -------+--------------------+------------------+----- | |
| 67 | - | | | | |
| 68 | - | CREATE TABLE... | | | |
| 69 | - |------------------->| | | |
| 70 | - | | send request | | |
| 71 | - | |----------------->| | |
| 72 | - | | | | |
| 73 | - | | success | | |
| 74 | - | |<-----------------| | |
| 75 | - | | | | |
| 76 | - | /--------------------\ | | |
| 77 | - | :Wait until all nodes+------>| | |
| 78 | - | :agree (or timeout) : | | |
| 79 | - | \--------------------/ | | |
| 80 | - | | ^ | | |
| 81 | - | | | | | |
| 82 | - | | +---------| | |
| 83 | - | | | | |
| 84 | - | | refresh schema | | |
| 85 | - | |----------------->| | |
| 86 | - | |<-----------------| | |
| 87 | - | complete query | | | |
| 88 | - |<-------------------| | | |
| 89 | - | | | | |
| 90 | -``` | |
| 91 | - | |
| 92 | -The schema agreement wait is performed synchronously, so the `execute` | |
| 93 | -call -- or the completion of the `ResultSetFuture` if you use the async | |
| 94 | -API -- will only return after it has completed. | |
| 95 | - | |
| 96 | -The check is implemented by repeatedly querying system tables for the | |
| 97 | -schema version reported by each node, until they all converge to the | |
| 98 | -same value. If that doesn't happen within a given timeout, the driver | |
| 99 | -will give up waiting. The default timeout is 10 seconds, it can be | |
| 100 | -customized when building your cluster: | |
| 101 | - | |
| 102 | -```java | |
| 103 | -Cluster cluster = Cluster.builder() | |
| 104 | - .addContactPoint("127.0.0.1") | |
| 105 | - .withMaxSchemaAgreementWaitSeconds(20) | |
| 106 | - .build(); | |
| 107 | -``` | |
| 108 | - | |
| 109 | -After executing a statement, you can check whether schema agreement was | |
| 110 | -successful or timed out: | |
| 111 | - | |
| 112 | -```java | |
| 113 | -ResultSet rs = session.execute("CREATE TABLE..."); | |
| 114 | -if (rs.getExecutionInfo().isSchemaInAgreement()) { | |
| 115 | - // schema is in agreement | |
| 116 | -} else { | |
| 117 | - // schema agreement timed out | |
| 118 | -} | |
| 119 | -``` | |
| 120 | - | |
| 121 | -You can also perform an on-demand check at any time: | |
| 122 | - | |
| 123 | -```java | |
| 124 | -if (cluster.getMetadata().checkSchemaAgreement()) { | |
| 125 | - // schema is in agreement | |
| 126 | -} else { | |
| 127 | - // schema is not in agreement | |
| 128 | -} | |
| 129 | -``` | |
| 130 | - | |
| 131 | -The on-demand check does not retry, it only queries system tables once | |
| 132 | -(so `maxSchemaAgreementWaitSeconds` does not apply). If you need | |
| 133 | -retries, you'll have to schedule them yourself (for example with a | |
| 134 | -custom executor). | |
| 135 | - | |
| 136 | -Check out the API docs for the features in this section: | |
| 137 | - | |
| 138 | -* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int)) | |
| 139 | -* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement()) | |
| 140 | -* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#checkSchemaAgreement()) | |
| 141 | - | |
| 142 | - | |
| 143 | -### Token metadata | |
| 144 | - | |
| 145 | -This feature is probably of less interest to regular driver users, but | |
| 146 | -it will be useful if you're writing an analytics client on top of the | |
| 147 | -driver. | |
| 148 | - | |
| 149 | -[Metadata][metadata] exposes a number of methods to manipulate tokens | |
| 150 | -and ranges: [getTokenRanges()][getTokenRanges], [getTokenRanges(String | |
| 151 | -keyspace, Host host)][getTokenRanges2], [getReplicas(String keyspace, | |
| 152 | -TokenRange range)][getReplicas], [newToken(String)][newToken] and | |
| 153 | -[newTokenRange(Token start, Token end)][newTokenRange]. | |
| 154 | - | |
| 155 | -[TokenRange][TokenRange] provides various operations on ranges | |
| 156 | -(splitting, merging, etc.). | |
| 157 | - | |
| 158 | -Each host exposes its primary tokens as [getTokens()][getTokens]. | |
| 159 | - | |
| 160 | -Finally, you can inject tokens in CQL queries with | |
| 161 | -[BoundStatement#setToken][setToken], and retrieve them from results with | |
| 162 | -[Row#getToken][getToken] and [Row#getPartitionKeyToken][getPKToken]. | |
| 163 | - | |
| 164 | -As an example, here is how you could compute the splits to partition a | |
| 165 | -job (pseudocode): | |
| 166 | - | |
| 167 | -``` | |
| 168 | -metadata = cluster.getMetadata() | |
| 169 | -for range : metadata.getTokenRanges() { | |
| 170 | - hosts = metadata.getReplicas(keyspace, range) | |
| 171 | - int n = estimateNumberOfSplits() // more on that below | |
| 172 | - for split : range.splitEvenly(n) | |
| 173 | - // pick a host to process split | |
| 174 | -} | |
| 175 | -``` | |
| 176 | - | |
| 177 | -For `estimateNumberOfSplits`, you need a way to estimate the total | |
| 178 | -number of partition keys (this is what analytics clients would | |
| 179 | -traditionally do with the Thrift operation `describe_splits_ex`). | |
| 180 | -Starting with Cassandra 2.1.5, this information is available in a system | |
| 181 | -table (see | |
| 182 | -[CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)). | |
| 183 | - | |
| 184 | -[metadata]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html | |
| 185 | -[getTokenRanges]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getTokenRanges() | |
| 186 | -[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host) | |
| 187 | -[getReplicas]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange) | |
| 188 | -[newToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#newToken(java.lang.String) | |
| 189 | -[newTokenRange]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token) | |
| 190 | -[TokenRange]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TokenRange.html | |
| 191 | -[getTokens]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Host.html#getTokens() | |
| 192 | -[setToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token) | |
| 193 | -[getToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Row.html#getToken(int) | |
| 194 | -[getPKToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Row.html#getPartitionKeyToken() |
deleted features/native_protocol/README.md +0 −101
| @@ -1,101 +0,0 @@ | ||
| 1 | -## Native protocol | |
| 2 | - | |
| 3 | -The native protocol defines the format of the binary messages exchanged | |
| 4 | -between the driver and Cassandra over TCP. As a driver user, you don't | |
| 5 | -need to know the fine details (although the protocol spec is [in the | |
| 6 | -Cassandra codebase][native_spec] if you're curious); the most visible | |
| 7 | -aspect is that some features are only available with specific protocol | |
| 8 | -versions. | |
| 9 | - | |
| 10 | -[native_spec]: https://github.com/apache/cassandra/tree/trunk/doc | |
| 11 | - | |
| 12 | -### Compatibility matrix | |
| 13 | - | |
| 14 | -By default, the protocol version is negotiated between the driver and | |
| 15 | -Cassandra when the first connection is established. Both sides are | |
| 16 | -backward-compatible with older versions: | |
| 17 | - | |
| 18 | -<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 19 | -<tr><td> </td><td>Cassandra: 1.2.x<br/>(DSE 3.2)</td><td>2.0.x<br/>(DSE 4.0 to 4.6)</td><td>2.1.x<br/>(DSE 4.7)</td></tr> | |
| 20 | -<tr><td>Driver: 1.0.x</td> <td>v1</td> <td>v1</td> <td>v1</td> </tr> | |
| 21 | -<tr><td>2.0.x to 2.1.1</td> <td>v1</td> <td>v2</td> <td>v2</td> </tr> | |
| 22 | -<tr><td>2.1.2 or more</td> <td>v1</td> <td>v2</td> <td>v3</td> </tr> | |
| 23 | -</table> | |
| 24 | - | |
| 25 | -For example, if you use version 2.1.5 of the driver to connect to | |
| 26 | -Cassandra 2.0.9, the maximum version you can use (and the one you'll get | |
| 27 | -by default) is protocol v2 (last line, middle column). If you use the | |
| 28 | -same version to connect to Cassandra 2.1.4, you can use protocol v3. | |
| 29 | - | |
| 30 | -### Controlling the protocol version | |
| 31 | - | |
| 32 | -To find out which version you're currently using, use | |
| 33 | -[ProtocolOptions#getProtocolVersionEnum()][gpve]: | |
| 34 | - | |
| 35 | -```java | |
| 36 | -ProtocolVersion myCurrentVersion = cluster.getConfiguration() | |
| 37 | - .getProtocolOptions() | |
| 38 | - .getProtocolVersionEnum(); | |
| 39 | -``` | |
| 40 | - | |
| 41 | -The protocol version can not be changed at runtime. However, you can | |
| 42 | -force a given version at initialization: | |
| 43 | - | |
| 44 | -```java | |
| 45 | -Cluster cluster = Cluster.builder() | |
| 46 | - .addContactPoint("127.0.0.1") | |
| 47 | - .withProtocolVersion(ProtocolVersion.V2) | |
| 48 | - .build(); | |
| 49 | -``` | |
| 50 | - | |
| 51 | -If you specify a version that is not compatible with your current | |
| 52 | -driver/Cassandra combination, you'll get an error: | |
| 53 | - | |
| 54 | -``` | |
| 55 | -Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException: | |
| 56 | -All host(s) tried for query failed | |
| 57 | -(tried: /127.0.0.1:9042 (com.datastax.driver.core.UnsupportedProtocolVersionException: | |
| 58 | - [/127.0.0.1:9042] Host /127.0.0.1:9042 does not support protocol version V3 but V2)) | |
| 59 | -``` | |
| 60 | - | |
| 61 | -[gpve]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersionEnum() | |
| 62 | - | |
| 63 | -#### Protocol version with mixed clusters | |
| 64 | - | |
| 65 | -If you have a cluster with mixed versions (for example, while doing a | |
| 66 | -rolling upgrade of Cassandra), note that **the protocol version will be | |
| 67 | -negotiated with the first host the driver connects to**. | |
| 68 | - | |
| 69 | -This could lead to the following situation (assuming you use driver | |
| 70 | -2.1.2+): | |
| 71 | - | |
| 72 | -* the first contact point is a 2.1 host, so the driver negotiates | |
| 73 | - protocol v3; | |
| 74 | -* while connecting to the rest of the cluster, the driver contacts a 2.0 | |
| 75 | - host using protocol v3, which fails; an error is logged and this host | |
| 76 | - will be permanently ignored. | |
| 77 | - | |
| 78 | -To avoid this issue, you can use one the following workarounds: | |
| 79 | - | |
| 80 | -* always force a protocol version at startup. You keep it at v2 while | |
| 81 | - the rolling upgrade is happening, and only switch to v3 when the whole | |
| 82 | - cluster has switched to Cassandra 2.1; | |
| 83 | -* ensure that the list of initial contact points only contains hosts | |
| 84 | - with the oldest version (2.0 in this example). | |
| 85 | - | |
| 86 | - | |
| 87 | -### New features by protocol version | |
| 88 | - | |
| 89 | -#### v1 to v2 | |
| 90 | - | |
| 91 | -* bound variables in simple statements | |
| 92 | - ([Session#execute(String, Object...)](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#execute(java.lang.String,%20java.lang.Object...))) | |
| 93 | -* [batch statements](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html) | |
| 94 | -* [query paging](../paging/) | |
| 95 | - | |
| 96 | -#### v2 to v3 | |
| 97 | - | |
| 98 | -* the number of stream ids per connection goes from 128 to 32768 (see | |
| 99 | - [Connection pooling](../pooling/)) | |
| 100 | -* [serial consistency on batch statements](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel(com.datastax.driver.core.ConsistencyLevel)) | |
| 101 | -* [client-side timestamps](../query_timestamps/) |
deleted features/object_mapper/README.md +0 −18
| @@ -1,18 +0,0 @@ | ||
| 1 | -# Object Mapper | |
| 2 | - | |
| 3 | -Version 2.1 of the driver introduces a simple object mapper, which | |
| 4 | -avoids most of the boilerplate when converting your domain classes to | |
| 5 | -and from query results. It handles basic CRUD operations in Cassandra tables | |
| 6 | -containing UDTs, collections and all native CQL types. | |
| 7 | - | |
| 8 | -The mapper is published as a separate Maven artifact: | |
| 9 | - | |
| 10 | -```xml | |
| 11 | -<dependency> | |
| 12 | - <groupId>com.datastax.cassandra</groupId> | |
| 13 | - <artifactId>cassandra-driver-mapping</artifactId> | |
| 14 | - <version>2.1.9</version> | |
| 15 | -</dependency> | |
| 16 | -``` | |
| 17 | - | |
| 18 | -This documentation is organized in subsections describing mapper features. |
deleted features/object_mapper/creating/README.md +0 −246
| @@ -1,246 +0,0 @@ | ||
| 1 | -## Definition of mapped classes | |
| 2 | - | |
| 3 | -The object mapper is configured by annotations on the mapped classes. | |
| 4 | - | |
| 5 | -### Creating a table entity | |
| 6 | - | |
| 7 | -A table entity is a class that will be mapped to a table in Cassandra. | |
| 8 | -It is annotated with [@Table][table]: | |
| 9 | - | |
| 10 | -``` | |
| 11 | -CREATE TABLE user (user_id uuid PRIMARY KEY, name text); | |
| 12 | -``` | |
| 13 | - | |
| 14 | -```java | |
| 15 | -@Table(keyspace = "ks", name = "users", | |
| 16 | - readConsistency = "QUORUM", | |
| 17 | - writeConsistency = "QUORUM", | |
| 18 | - caseSensitiveKeyspace = false, | |
| 19 | - caseSensitiveTable = false) | |
| 20 | -public static class User { | |
| 21 | - @PartitionKey | |
| 22 | - @Column(name = "user_id") | |
| 23 | - private UUID userId; | |
| 24 | - private String name; | |
| 25 | - // ... constructors / getters / setters | |
| 26 | -} | |
| 27 | -``` | |
| 28 | - | |
| 29 | -`@Table` takes the following options: | |
| 30 | - | |
| 31 | -- `keyspace`: the keyspace for the table. | |
| 32 | -- `name`: the name of the table in the database. | |
| 33 | -- `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive]. | |
| 34 | -- `caseSensitiveTable`: whether the table name is [case-sensitive]. | |
| 35 | -- `readConsistency`: the [consistency level] that will be used on each | |
| 36 | - get operation in the mapper. (if unspecified, it defaults to the | |
| 37 | - cluster-wide setting) | |
| 38 | -- `writeConsistency`: the [consistency level] that will be used on each | |
| 39 | - save, or delete operation in the mapper. (if unspecified, it defaults | |
| 40 | - to the cluster-wide setting) | |
| 41 | - | |
| 42 | -The class must provide a default constructor, and all fields (except the | |
| 43 | -ones annotated `@Transient`) must have corresponding setters and | |
| 44 | -getters. | |
| 45 | - | |
| 46 | -[table]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Table.html | |
| 47 | -[case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html | |
| 48 | -[consistency level]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ConsistencyLevel.html | |
| 49 | - | |
| 50 | -#### Column names | |
| 51 | - | |
| 52 | -By default, the mapper tries to map each Java property to a | |
| 53 | -case insensitive column of the same name. If you want to use a different | |
| 54 | -name, or [case-sensitive] names, use the [@Column][column] annotation on | |
| 55 | -the field. | |
| 56 | - | |
| 57 | -[column]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Column.html | |
| 58 | - | |
| 59 | -#### Primary key fields | |
| 60 | - | |
| 61 | -[@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the | |
| 62 | -[partition key][pks] and [clustering columns][pks]. In the case of a | |
| 63 | -composite partition key or multiple clustering columns, the integer | |
| 64 | -value indicates the position of the column in the key: | |
| 65 | - | |
| 66 | -``` | |
| 67 | -CREATE TABLE sales(countryCode text, areaCode text, sales int, | |
| 68 | - PRIMARY KEY((countryCode, area Code))); | |
| 69 | -``` | |
| 70 | - | |
| 71 | -```java | |
| 72 | -@PartitionKey(0) | |
| 73 | -private String countryCode; | |
| 74 | -@PartitionKey(1) | |
| 75 | -private String areaCode; | |
| 76 | -``` | |
| 77 | - | |
| 78 | -The order of the indices must match that of the columns in the table | |
| 79 | -declaration. | |
| 80 | - | |
| 81 | -[pk]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/PartitionKey.html | |
| 82 | -[cc]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/ClusteringColumn.html | |
| 83 | -[pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html | |
| 84 | - | |
| 85 | -#### Enumerations | |
| 86 | - | |
| 87 | -[@Enumerated][enum] is used to map Java enumerations. Since Cassandra | |
| 88 | -does not support enumerations, the object mapper defines two ways to | |
| 89 | -persist an enum value : | |
| 90 | - | |
| 91 | -- `EnumType.ORDINAL` : the value is persisted as a Cassandra's `int` and | |
| 92 | - its value is its position in the enum. | |
| 93 | -- `EnumType.STRING` : the value is persisted as a Cassandra's `text` and | |
| 94 | - its value is its name in the enum. | |
| 95 | - | |
| 96 | -According to the chosen type, the matching database column must be the | |
| 97 | -same type. | |
| 98 | - | |
| 99 | -``` | |
| 100 | -CREATE TABLE person (id uuid PRIMARY KEY, name text, gender int); | |
| 101 | -``` | |
| 102 | - | |
| 103 | -```java | |
| 104 | -@Enumerated(EnumType.ORDINAL) | |
| 105 | -private Gender gender; | |
| 106 | -``` | |
| 107 | - | |
| 108 | -[enum]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Enumerated.html | |
| 109 | - | |
| 110 | -#### Computed fields | |
| 111 | - | |
| 112 | -[@Computed][computed] can be used on fields that are the result of a | |
| 113 | -computation on the Cassandra side. Typically a function call. Native | |
| 114 | -functions in Cassandra like `writetime()` or [User Defined Functions] are | |
| 115 | -supported. | |
| 116 | - | |
| 117 | -```java | |
| 118 | -@Computed("ttl(name)") | |
| 119 | -Integer ttl; | |
| 120 | -``` | |
| 121 | - | |
| 122 | -The CQL return type of function must match the type of the field, | |
| 123 | -otherwise an exception will be thrown. | |
| 124 | - | |
| 125 | -Computed fields are ignored when saving an entity. | |
| 126 | - | |
| 127 | -`@Computed` does not support case-sensitivity. If the expression | |
| 128 | -contains case-sensitive column or function names, you'll have to escape | |
| 129 | -them: | |
| 130 | - | |
| 131 | -```java | |
| 132 | -@Computed("\"myFunction\"(\"myColumn\")") | |
| 133 | -int f; | |
| 134 | -``` | |
| 135 | - | |
| 136 | -Finally, computed fields are only supported with [basic read | |
| 137 | -operations](../using/#basic-crud-operations) at this time. | |
| 138 | -Support in [accessors](../using/#accessors) in planned for a future | |
| 139 | -version (see | |
| 140 | -[JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). | |
| 141 | - | |
| 142 | -[User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ | |
| 143 | -[computed]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Computed.html | |
| 144 | - | |
| 145 | -#### Transient fields | |
| 146 | - | |
| 147 | -[@Transient][transient] can be used to prevent a field from being mapped. | |
| 148 | - | |
| 149 | -[transient]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Transient.html | |
| 150 | - | |
| 151 | -### Mapping User Types | |
| 152 | - | |
| 153 | -[User Defined Types] can also be mapped by using [@UDT][udt]: | |
| 154 | - | |
| 155 | -``` | |
| 156 | -CREATE TYPE address (street text, zip_code int); | |
| 157 | -``` | |
| 158 | - | |
| 159 | -```java | |
| 160 | -@UDT(keyspace = "ks", name = "address") | |
| 161 | -class Address { | |
| 162 | - private String street; | |
| 163 | - @Field(name = "zip_code") | |
| 164 | - private int zipCode; | |
| 165 | - // ... constructors / getters / setters | |
| 166 | -} | |
| 167 | -``` | |
| 168 | - | |
| 169 | -`@UDT` takes the following options: | |
| 170 | - | |
| 171 | -- `keyspace`: the keyspace for the UDT. | |
| 172 | -- `name`: the name of the UDT in the database. | |
| 173 | -- `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. | |
| 174 | -- `caseSensitiveType`: whether the UDT name is case-sensitive. | |
| 175 | - | |
| 176 | -The class must provide a default constructor, and all fields (except the | |
| 177 | -ones annotated `@Transient`) must have corresponding setters and | |
| 178 | -getters. | |
| 179 | - | |
| 180 | -As in table entities, fields are mapped to an UDT field of the same | |
| 181 | -name by default. To declare a different name or use case-sensitivity, | |
| 182 | -use the [@Field][field] annotation: | |
| 183 | - | |
| 184 | -```java | |
| 185 | -@Field(name = "zip_code") | |
| 186 | -private int zipCode; | |
| 187 | -``` | |
| 188 | - | |
| 189 | -When a table has a UDT column, the mapper will automatically map it to | |
| 190 | -the corresponding class: | |
| 191 | - | |
| 192 | -``` | |
| 193 | -CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address); | |
| 194 | -``` | |
| 195 | - | |
| 196 | -```java | |
| 197 | -public static class Company { | |
| 198 | - @PartitionKey | |
| 199 | - @Column(name = "company_id") | |
| 200 | - private UUID companyId; | |
| 201 | - private String name; | |
| 202 | - private Address address; | |
| 203 | -} | |
| 204 | -``` | |
| 205 | - | |
| 206 | -(this also works with UDTs inside collections or other UDTs, with | |
| 207 | -arbitrary level of nesting) | |
| 208 | - | |
| 209 | -[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html | |
| 210 | -[udt]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/UDT.html | |
| 211 | -[field]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Field.html | |
| 212 | - | |
| 213 | -### Mapping collections | |
| 214 | - | |
| 215 | -Java collections will be automatically mapped into corresponding | |
| 216 | -Cassandra types. As in Cassandra, collections can contain all native | |
| 217 | -types and all [user types](#mapping-user-types) previously defined is | |
| 218 | -the database. | |
| 219 | - | |
| 220 | -Collection fields must be annotated to indicate whether they are frozen | |
| 221 | -or not (currently this is only for informational purposes, but the | |
| 222 | -mapper will check that the declared state match the rules in Cassandra). | |
| 223 | -The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and | |
| 224 | -[@FrozenValue][frozenvalue]` are also provided for convenience: | |
| 225 | - | |
| 226 | -```java | |
| 227 | -// Will be mapped as a 'list<text>' | |
| 228 | -private List<String> stringList; | |
| 229 | - | |
| 230 | -// Will be mapped as a 'frozen<list<text>>' | |
| 231 | -@Frozen | |
| 232 | -private List<String> frozenStringList; | |
| 233 | - | |
| 234 | -// Will be mapped as 'map<frozen<address>, frozen<list<text>>>' | |
| 235 | -@FrozenKey | |
| 236 | -@FrozenValue | |
| 237 | -private Map<Address, List<String>> frozenKeyValueMap; | |
| 238 | - | |
| 239 | -// Will be mapped as 'map<text, frozen<list<address>>>' | |
| 240 | -@FrozenValue | |
| 241 | -private Map<String, List<Address>> frozenValueMap; | |
| 242 | -``` | |
| 243 | - | |
| 244 | -[frozen]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Frozen.html | |
| 245 | -[frozenkey]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/FrozenKey.html | |
| 246 | -[frozenvalue]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/FrozenValue.html |
deleted features/object_mapper/using/README.md +0 −313
| @@ -1,313 +0,0 @@ | ||
| 1 | -## Using the mapper | |
| 2 | - | |
| 3 | -First, create a [MappingManager]. It wraps an existing [Session] | |
| 4 | -instance: | |
| 5 | - | |
| 6 | -```java | |
| 7 | -MappingManager manager = new MappingManager(session); | |
| 8 | -``` | |
| 9 | - | |
| 10 | -`MappingManager` is thread-safe and can be safely shared throughout your | |
| 11 | -application. You would typically create one instance at startup, right | |
| 12 | -after your `Session`. | |
| 13 | - | |
| 14 | -Note that `MappingManager` will initialize the `Session` if not | |
| 15 | -previously done (this was not the case in previous driver versions; if | |
| 16 | -this is a problem for you, see `MappingManager(session, protocolVersion)`). | |
| 17 | - | |
| 18 | -### Entity mappers | |
| 19 | - | |
| 20 | -Each entity class (annotated with `@Table`) is managed by a dedicated | |
| 21 | -[Mapper] object. You obtain this object from the `MappingManager`: | |
| 22 | - | |
| 23 | -```java | |
| 24 | -Mapper<User> mapper = manager.mapper(User.class); | |
| 25 | -``` | |
| 26 | - | |
| 27 | -`Mapper` objects are thread-safe. The manager caches them internally, so | |
| 28 | -calling `manager#mapper` more than once for the same class will return | |
| 29 | -the previously generated mapper. | |
| 30 | - | |
| 31 | -[Mapper]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/Mapper.html | |
| 32 | -[MappingManager]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/MappingManager.html | |
| 33 | -[Session]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html | |
| 34 | - | |
| 35 | -#### Basic CRUD operations | |
| 36 | - | |
| 37 | -To save an object, use `Mapper#save`: | |
| 38 | - | |
| 39 | -```java | |
| 40 | -UUID userId = ...; | |
| 41 | -User u = new User(userId, "John Doe", new Address("street", 01000)); | |
| 42 | -mapper.save(u); | |
| 43 | -``` | |
| 44 | - | |
| 45 | --------------- | |
| 46 | - | |
| 47 | -To retrieve an object, use `Mapper#get`: | |
| 48 | - | |
| 49 | -```java | |
| 50 | -UUID userId = ...; | |
| 51 | -User u = mapper.get(userId); | |
| 52 | -``` | |
| 53 | - | |
| 54 | -`get`'s arguments must match the partition key components (number of | |
| 55 | -arguments and their types). | |
| 56 | - | |
| 57 | --------------- | |
| 58 | - | |
| 59 | -To delete a row in a table, use `Mapper#delete`. This method support | |
| 60 | -deleting a row given either its primary keys, or the object to delete: | |
| 61 | - | |
| 62 | -```java | |
| 63 | -UUID userId = ...; | |
| 64 | -mapper.delete(userId); | |
| 65 | -mapper.delete(u); | |
| 66 | -``` | |
| 67 | - | |
| 68 | --------------- | |
| 69 | - | |
| 70 | -All these CRUD operations are synchronous, but the `Mapper` provides | |
| 71 | -their asynchronous equivalents: | |
| 72 | - | |
| 73 | -```java | |
| 74 | -ListenableFuture<Void> saveFuture = mapper.saveAsync(u); | |
| 75 | -ListenableFuture<User> userFuture = mapper.getAsync(userId); | |
| 76 | -ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId); | |
| 77 | -``` | |
| 78 | - | |
| 79 | -#### Mapper options | |
| 80 | - | |
| 81 | -The basic CRUD operations accept additional options to customize the | |
| 82 | -underlying query: | |
| 83 | - | |
| 84 | -- `ttl`: add a time-to-live value for the operation. | |
| 85 | -- `timestamp`: add a timestamp value for the operation. | |
| 86 | -- `consistencyLevel`: specify a consistency level. | |
| 87 | -- `tracing`: set tracing flag for the query. | |
| 88 | -- `saveNullFields`: if set to true, fields with value `null` in an | |
| 89 | - instance that is to be persisted will be explicitly written as `null` | |
| 90 | - in the query. If set to false, fields with null value won't be included | |
| 91 | - in the write query (thus avoiding tombstones). If not specified, the | |
| 92 | - default behavior is to persist `null` fields. | |
| 93 | - | |
| 94 | -To use options, add them to the mapper call after regular parameters: | |
| 95 | - | |
| 96 | -```java | |
| 97 | -import static com.datastax.driver.mapping.Mapper.Option.*; | |
| 98 | - | |
| 99 | -mapper.save(new User(userId, "helloworld"), | |
| 100 | - timestamp(123456L), tracing(true), ttl(42)); | |
| 101 | -``` | |
| 102 | - | |
| 103 | -Some options don't apply to all operations: | |
| 104 | - | |
| 105 | -<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 106 | - <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr> | |
| 107 | - <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr> | |
| 108 | - <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr> | |
| 109 | - <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> | |
| 110 | - <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> | |
| 111 | - <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr> | |
| 112 | -</table> | |
| 113 | - | |
| 114 | -Note that `Option.consistencyLevel` is redundant with the consistency | |
| 115 | -level defined by [@Table](../creating/#creating-a-table-entity). | |
| 116 | -If both are defined, the option will take precedence over the | |
| 117 | -annotation. | |
| 118 | - | |
| 119 | -Default options can be defined for each type of operation: | |
| 120 | - | |
| 121 | -```java | |
| 122 | -mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM)); | |
| 123 | -mapper.setDefaultSaveOption(saveNullFields(false)); | |
| 124 | -mapper.setDefaultDeleteOption(consistencyLevel(ONE)); | |
| 125 | - | |
| 126 | -// Given the defaults above, this will use tracing(true), consistencyLevel(ONE) | |
| 127 | -mapper.get(uuid, consistencyLevel(ONE)); | |
| 128 | -``` | |
| 129 | - | |
| 130 | -To reset default options, use the following methods: | |
| 131 | - | |
| 132 | -```java | |
| 133 | -mapper.resetDefaultGetOption(); | |
| 134 | -mapper.resetDefaultSaveOption(); | |
| 135 | -mapper.resetDefaultDeleteOption(); | |
| 136 | -``` | |
| 137 | - | |
| 138 | -#### Access to underlying `Statement`s | |
| 139 | - | |
| 140 | -Instead of performing an operation directly, it's possible to ask the | |
| 141 | -`Mapper` to just return the corresponding `Statement` object. This gives | |
| 142 | -the client a chance to customize the statement before executing it. | |
| 143 | - | |
| 144 | -- `Mapper.saveQuery(entity)`: returns a statement generated by the | |
| 145 | - mapper to save `entity` into the database. | |
| 146 | -- `Mapper.getQuery(userId)`: returns a statement to select a row in the | |
| 147 | - database, selected on the given `userId`, and matching the mapped | |
| 148 | - object structure. | |
| 149 | -- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the | |
| 150 | - database given the `userId` provided. This method can also accept a | |
| 151 | - mapped object instance. | |
| 152 | - | |
| 153 | -#### Manual mapping | |
| 154 | - | |
| 155 | -`Mapper#map` provides a way to converts the results of a regular query: | |
| 156 | - | |
| 157 | -```java | |
| 158 | -ResultSet results = session.execute("SELECT * FROM user"); | |
| 159 | -Result<User> users = mapper.map(results); | |
| 160 | -for (User u : users) { | |
| 161 | - System.out.println("User : " + u.getUserId()); | |
| 162 | -} | |
| 163 | -``` | |
| 164 | - | |
| 165 | -This method will ignore: | |
| 166 | - | |
| 167 | -* extra columns in the `ResultSet` that are not mapped for this entity. | |
| 168 | -* mapped fields that are not present in the `ResultSet` (setters won't | |
| 169 | - be called so the value will be the one after invocation of the class's | |
| 170 | - default constructor). | |
| 171 | - | |
| 172 | -[Result] is similar to `ResultSet` but for a given mapped class. | |
| 173 | -It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()` | |
| 174 | -and `isExhausted()`. Note that iterating the `Result` will consume the | |
| 175 | -`ResultSet`, and vice-versa. | |
| 176 | - | |
| 177 | -[Result]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/Result.html | |
| 178 | - | |
| 179 | -### UDT Mappers | |
| 180 | - | |
| 181 | -A UDT will be automatically mapped when it is part of a table-level | |
| 182 | -class (as shown [here](../creating/#mapping-user-types)). | |
| 183 | - | |
| 184 | -However, there might be cases where it is useful to convert a mapped | |
| 185 | -instance to the corresponding [UDTValue][UDTValue] (and back). The | |
| 186 | -mapper provides an [UDTMapper] for that purpose: | |
| 187 | - | |
| 188 | -```java | |
| 189 | -UDTMapper<Address> addressMapper = manager.getUDTMapper(Address.class); | |
| 190 | -Address address = addressMapper.fromUDT(udtValue); | |
| 191 | -UDTValue value = addressMapper.toUDT(address); | |
| 192 | -``` | |
| 193 | - | |
| 194 | -[UDTValue]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/UDTValue.html | |
| 195 | -[UDTMapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/UDTMapper.html | |
| 196 | - | |
| 197 | -### Accessors | |
| 198 | - | |
| 199 | -`Accessor`s provide a way to map custom queries not supported by the | |
| 200 | -default entity mappers. | |
| 201 | - | |
| 202 | -To create an accessor, define a Java interface and annotate each method | |
| 203 | -to provide the corresponding CQL query: | |
| 204 | - | |
| 205 | -```java | |
| 206 | -@Accessor | |
| 207 | -public interface UserAccessor { | |
| 208 | - @Query("SELECT * FROM user") | |
| 209 | - Result<User> getAll(); | |
| 210 | -} | |
| 211 | -``` | |
| 212 | - | |
| 213 | -The `MappingManager` can then process this class and generate an | |
| 214 | -implementation: | |
| 215 | - | |
| 216 | -```java | |
| 217 | -UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); | |
| 218 | -User user = userAccessor.getOne(uuid); | |
| 219 | -``` | |
| 220 | - | |
| 221 | -Like mappers, accessors are cached at the manager level and thus, are | |
| 222 | -thread-safe/sharable. | |
| 223 | - | |
| 224 | -#### Parameters | |
| 225 | - | |
| 226 | -A query can have bind markers, that will be set with the method's | |
| 227 | -arguments. | |
| 228 | - | |
| 229 | -With unnamed markers, the order of the arguments must match the order of | |
| 230 | -the markers: | |
| 231 | - | |
| 232 | -```java | |
| 233 | -@Query("insert into user (id, name) values (?, ?)") | |
| 234 | -ResultSet insert(UUID userId, String name); | |
| 235 | -``` | |
| 236 | - | |
| 237 | -With named markers, use [@Param][param] to indicate which parameter | |
| 238 | -corresponds to which marker: | |
| 239 | - | |
| 240 | -```java | |
| 241 | -@Query("insert into user (userId, name) values (:u, :n)") | |
| 242 | -ResultSet insert(@Param("u") UUID userId, @Param("n") String name); | |
| 243 | -``` | |
| 244 | - | |
| 245 | -[param]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Param.html | |
| 246 | - | |
| 247 | -If a method argument is a Java enumeration, it must be annotated with | |
| 248 | -`@Enumerated` to indicate how to convert it to a CQL type (the rules are | |
| 249 | -the same as in [mapping definition](../creating/#enumerations)): | |
| 250 | - | |
| 251 | -```java | |
| 252 | -@Query("insert into user (key, gender) values (?,?)") | |
| 253 | -ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value); | |
| 254 | -``` | |
| 255 | - | |
| 256 | -#### Return type | |
| 257 | - | |
| 258 | -The declared return type of each method affects how the query will get | |
| 259 | -executed: | |
| 260 | - | |
| 261 | -<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 262 | - <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr> | |
| 263 | - <tr> | |
| 264 | - <td><code>void</code></td> | |
| 265 | - <td>Synchronous execution, discards the results of the query.</td> | |
| 266 | - </tr> | |
| 267 | - <tr> | |
| 268 | - <td><code>ResultSet</code></td> | |
| 269 | - <td>Synchronous execution, returns unmapped results.</td> | |
| 270 | - </tr> | |
| 271 | - <tr> | |
| 272 | - <td><code>T</code></td> | |
| 273 | - <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td> | |
| 274 | - </tr> | |
| 275 | - <tr> | |
| 276 | - <td><code>Result<T></code></td> | |
| 277 | - <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td> | |
| 278 | - </tr> | |
| 279 | - <tr> | |
| 280 | - <td><code>ResultSetFuture</code></td> | |
| 281 | - <td>Asynchronous execution, returns unmapped results.</td> | |
| 282 | - </tr> | |
| 283 | - <tr> | |
| 284 | - <td><code>ListenableFuture<T></code></td> | |
| 285 | - <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td> | |
| 286 | - </tr> | |
| 287 | - <tr> | |
| 288 | - <td><code>ListenableFuture<Result<T>></code></td> | |
| 289 | - <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td> | |
| 290 | - </tr> | |
| 291 | -</table> | |
| 292 | - | |
| 293 | -Example: | |
| 294 | - | |
| 295 | -```java | |
| 296 | -@Query("SELECT * FROM user") | |
| 297 | -public ListenableFuture<Result<User>> getAllAsync(); | |
| 298 | -``` | |
| 299 | - | |
| 300 | - | |
| 301 | -#### Customizing the statement | |
| 302 | - | |
| 303 | -It is possible to customize query parameters to include in a `Accessor` | |
| 304 | -query with the annotation [@QueryParameters]. Then, options like | |
| 305 | -*consistency level*, *fetchsize* or *tracing* are settable: | |
| 306 | - | |
| 307 | -```java | |
| 308 | -@Query("SELECT * FROM ks.users") | |
| 309 | -@QueryParameters(consistency="QUORUM") | |
| 310 | -public ListenableFuture<Result<User>> getAllAsync(); | |
| 311 | -``` | |
| 312 | - | |
| 313 | -[@QueryParameters]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/QueryParameters.html |
deleted features/paging/README.md +0 −269
| @@ -1,269 +0,0 @@ | ||
| 1 | -## Paging | |
| 2 | - | |
| 3 | -When a query returns many rows, it would be inefficient to return them | |
| 4 | -as a single response message. Instead, the driver breaks the results | |
| 5 | -into *pages* which get returned as they are needed. | |
| 6 | - | |
| 7 | -### Setting the fetch size | |
| 8 | - | |
| 9 | -The *fetch size* specifies how many rows will be returned at once by | |
| 10 | -Cassandra (in other words, it's the size of each page). | |
| 11 | - | |
| 12 | -You can set a default fetch size globally for a `Cluster` instance: | |
| 13 | - | |
| 14 | -```java | |
| 15 | -// At initialization: | |
| 16 | -Cluster cluster = Cluster.builder() | |
| 17 | - .addContactPoint("127.0.0.1") | |
| 18 | - .withQueryOptions(new QueryOptions().setFetchSize(2000)) | |
| 19 | - .build(); | |
| 20 | - | |
| 21 | -// Or at runtime: | |
| 22 | -cluster.getConfiguration().getQueryOptions().setFetchSize(2000); | |
| 23 | -``` | |
| 24 | - | |
| 25 | -The fetch size can also be set on a statement: | |
| 26 | - | |
| 27 | -```java | |
| 28 | -Statement statement = new SimpleStatement("your query"); | |
| 29 | -statement.setFetchSize(2000); | |
| 30 | -``` | |
| 31 | - | |
| 32 | -If the fetch size is set on a statement, it will take precedence; | |
| 33 | -otherwise, the cluster-wide value (which defaults to 5000) will be used. | |
| 34 | - | |
| 35 | -Note that setting a fetch size doesn't mean that Cassandra will always | |
| 36 | -return the exact number of rows, it is possible that it returns slightly | |
| 37 | -more or less results. | |
| 38 | - | |
| 39 | -### Result set iteration | |
| 40 | - | |
| 41 | -The fetch size limits the number of results that are returned in one | |
| 42 | -page; if you iterate past that, the driver will run background queries | |
| 43 | -to fetch subsequent pages. Here's an example with a fetch size of 20: | |
| 44 | - | |
| 45 | -```ditaa | |
| 46 | - client Session Cassandra | |
| 47 | - --+--------------+---------------------------------+----- | |
| 48 | - |execute(query)| | | |
| 49 | - |------------->| | | |
| 50 | - | | query rows 1 to 20 | | |
| 51 | - | |-------------------------------->| | |
| 52 | - | | | | |
| 53 | - | |create | | |
| 54 | - | |------>ResultSet | | |
| 55 | - | | | | |
| 56 | -+-----+--------+-----------------+-+ | | |
| 57 | -|For i in 1..20| | | | | |
| 58 | -+--------------+ | | | | |
| 59 | -| | get next row | | | | |
| 60 | -| |------------------------->| | | | |
| 61 | -| | row i | | | | |
| 62 | -| |<-------------------------| | | | |
| 63 | -| | | | | | |
| 64 | -+-----+--------------------------+-+ | | |
| 65 | - | | | | |
| 66 | - | | | | |
| 67 | - | get next row | | | |
| 68 | - |------------------------->| | | |
| 69 | - | | query rows 21 to 40 | | |
| 70 | - | |-------------------->| | |
| 71 | - | row 21 | | | |
| 72 | - |<------------------------ | | | |
| 73 | -``` | |
| 74 | - | |
| 75 | -By default, the background fetch happens at the last moment, when there | |
| 76 | -are no more "local" rows available. If you need finer control, the | |
| 77 | -[ResultSet][result_set] interface provides the following methods: | |
| 78 | - | |
| 79 | -* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the | |
| 80 | - current state; | |
| 81 | -* `fetchMoreResults()` to force a page fetch. | |
| 82 | - | |
| 83 | -Here's how you could use these methods to pre-fetch the next page in | |
| 84 | -advance, in order to avoid the performance hit at the end of each page: | |
| 85 | - | |
| 86 | -```java | |
| 87 | -ResultSet rs = session.execute("your query"); | |
| 88 | -for (Row row : rs) { | |
| 89 | - if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched()) | |
| 90 | - rs.fetchMoreResults(); // this is asynchronous | |
| 91 | - // Process the row ... | |
| 92 | - System.out.println(row); | |
| 93 | -} | |
| 94 | -``` | |
| 95 | - | |
| 96 | -If you use paging with the async API, you'll also want to use those | |
| 97 | -methods to avoid triggering synchronous fetches unintentionally; see | |
| 98 | -[async paging](../async/#async-paging). | |
| 99 | - | |
| 100 | - | |
| 101 | -### Saving and reusing the paging state | |
| 102 | - | |
| 103 | -Sometimes it is convenient to save the paging state in order to restore | |
| 104 | -it later. For example, consider a stateless web service that displays a | |
| 105 | -list of results with a link to the next page. When the user clicks that | |
| 106 | -link, we want to run the exact same query, except that the iteration | |
| 107 | -should start where we stopped on the previous page. | |
| 108 | - | |
| 109 | -To do so, the driver exposes a [PagingState][paging_state] object that represents | |
| 110 | -where we were in the result set when the last page was fetched: | |
| 111 | - | |
| 112 | -```java | |
| 113 | -ResultSet resultSet = session.execute("your query"); | |
| 114 | -// iterate the result set... | |
| 115 | -PagingState pagingState = resultSet.getExecutionInfo().getPagingState(); | |
| 116 | -``` | |
| 117 | - | |
| 118 | -This object can be serialized to a `String` or a byte array: | |
| 119 | - | |
| 120 | -```java | |
| 121 | -String string = pagingState.toString(); | |
| 122 | -byte[] bytes = pagingState.toBytes(); | |
| 123 | -``` | |
| 124 | - | |
| 125 | -This serialized form can be saved in some form of persistent storage to | |
| 126 | -be reused later. In our web service example, we would probably save the | |
| 127 | -string version as a query parameter in the URL to the next page | |
| 128 | -(`http://myservice.com/results?page=<...>`). When that value is | |
| 129 | -retrieved later, we can deserialize it and reinject it in a statement: | |
| 130 | - | |
| 131 | -```java | |
| 132 | -PagingState pagingState = PagingState.fromString(string); | |
| 133 | -Statement st = new SimpleStatement("your query"); | |
| 134 | -st.setPagingState(pagingState); | |
| 135 | -ResultSet rs = session.execute(st); | |
| 136 | -``` | |
| 137 | - | |
| 138 | -Note that the paging state can only be reused with the exact same | |
| 139 | -statement (same query string, same parameters). Also, it is an opaque | |
| 140 | -value that is only meant to be collected, stored an re-used. If you try | |
| 141 | -to modify its contents or reuse it with a different statement, the | |
| 142 | -driver will raise an error. | |
| 143 | - | |
| 144 | -Putting it all together, here's a more comprehensive example | |
| 145 | -implementation for our web service: | |
| 146 | - | |
| 147 | -```java | |
| 148 | -final int RESULTS_PER_PAGE = 100; | |
| 149 | - | |
| 150 | -Statement st = new SimpleStatement("your query"); | |
| 151 | -st.setFetchSize(RESULTS_PER_PAGE); | |
| 152 | - | |
| 153 | -String requestedPage = extractPagingStateStringFromURL(); | |
| 154 | -// This will be absent for the first page | |
| 155 | -if (requestedPage != null) { | |
| 156 | - st.setPagingState( | |
| 157 | - PagingState.fromString(requestedPage)); | |
| 158 | -} | |
| 159 | - | |
| 160 | -ResultSet rs = session.execute(st); | |
| 161 | -PagingState nextPage = rs.getExecutionInfo().getPagingState(); | |
| 162 | - | |
| 163 | -// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might | |
| 164 | -// have not respected it, or we might be at the end of the result set | |
| 165 | -int remaining = rs.getAvailableWithoutFetching(); | |
| 166 | -for (Row row : rs) { | |
| 167 | - renderInResponse(row); | |
| 168 | - if (--remaining == 0) { | |
| 169 | - break; | |
| 170 | - } | |
| 171 | -} | |
| 172 | - | |
| 173 | -// This will be null if there are no more pages | |
| 174 | -if (nextPage != null) { | |
| 175 | - renderNextPageLink(nextPage.toString()); | |
| 176 | -} | |
| 177 | -``` | |
| 178 | - | |
| 179 | -[result_set]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html | |
| 180 | -[paging_state]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PagingState.html | |
| 181 | - | |
| 182 | - | |
| 183 | -Due to internal implementation details, `PagingState` instances are not | |
| 184 | -portable across [native protocol](../native_protocol/) versions. This | |
| 185 | -could become a problem in the following scenario: | |
| 186 | - | |
| 187 | -* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore | |
| 188 | - native protocol v2; | |
| 189 | -* a user bookmarks a link to your web service that contains a serialized | |
| 190 | - paging state; | |
| 191 | -* you upgrade your server stack to use the driver 2.1.x and Cassandra | |
| 192 | - 2.1.x, so you're now using protocol v3; | |
| 193 | -* the user tries to reload their bookmark, but the paging state was | |
| 194 | - serialized with protocol v2, so trying to reuse it will fail. | |
| 195 | - | |
| 196 | -If this is not acceptable for you, you might want to consider the unsafe | |
| 197 | -API described in the next section. | |
| 198 | - | |
| 199 | -#### Unsafe API | |
| 200 | - | |
| 201 | -As an alternative to the standard API, there are two methods that | |
| 202 | -manipulate a raw `byte[]` instead of a `PagingState` object: | |
| 203 | - | |
| 204 | -* [ExecutionInfo#getPagingStateUnsafe()][gpsu] | |
| 205 | -* [Statement#setPagingStateUnsafe(byte[])][spsu] | |
| 206 | - | |
| 207 | -These low-level methods perform no validation on their arguments; | |
| 208 | -therefore nothing protects you from reusing a paging state that was | |
| 209 | -generated from a different statement, or altered in any way. This could | |
| 210 | -result in sending a corrupt paging state to Cassandra, with | |
| 211 | -unpredictable consequences (ranging from wrong results to a query | |
| 212 | -failure). | |
| 213 | - | |
| 214 | -There are two situations where you might want to use the unsafe API: | |
| 215 | - | |
| 216 | -* you never expose the paging state to end users and you are confident | |
| 217 | - that it won't get altered; | |
| 218 | -* you want portability across protocol versions and/or you prefer | |
| 219 | - implementing your own validation logic (for example, signing the raw | |
| 220 | - state with a private key). | |
| 221 | - | |
| 222 | -[gpsu]: http://www.datastax.com/drivers/java/2.1/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe() | |
| 223 | -[spsu]: http://www.datastax.com/drivers/java/2.1/com/datastax/driver/core/Statement.html#setPagingStateUnsafe(byte[]) | |
| 224 | - | |
| 225 | - | |
| 226 | -### Offset queries | |
| 227 | - | |
| 228 | -Saving the paging state works well when you only let the user move from | |
| 229 | -one page to the next. But it doesn't allow random jumps (like "go | |
| 230 | -directly to page 10"), because you can't fetch a page unless you have | |
| 231 | -the paging state of the previous one. Such a feature would require | |
| 232 | -*offset queries*, but they are not natively supported by Cassandra (see | |
| 233 | -[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)). | |
| 234 | -The rationale is that offset queries are inherently inefficient (the | |
| 235 | -performance will always be linear in the number of rows skipped), so the | |
| 236 | -Cassandra team doesn't want to encourage their use. | |
| 237 | - | |
| 238 | -If you really want offset queries, you can emulate them client-side. | |
| 239 | -You'll still get linear performance, but maybe that's acceptable for | |
| 240 | -your use case. For example, if each page holds 10 rows and you show at | |
| 241 | -most 20 pages, this means you'll fetch at most 190 extra rows, which | |
| 242 | -doesn't sound like a big deal. | |
| 243 | - | |
| 244 | -For example, if the page size is 10, the fetch size is 50, and the user | |
| 245 | -asks for page 12 (rows 110 to 119): | |
| 246 | - | |
| 247 | -* execute the statement a first time (the result set contains rows 0 to | |
| 248 | - 49, but you're not going to use them, only the paging state); | |
| 249 | -* execute the statement a second time with the paging state from the | |
| 250 | - first query; | |
| 251 | -* execute the statement a third time with the paging state from the | |
| 252 | - second query. The result set now contains rows 100 to 149; | |
| 253 | -* skip the first 10 rows of the iterator. Read the next 10 rows and | |
| 254 | - discard the remaining ones. | |
| 255 | - | |
| 256 | -You'll want to experiment with the fetch size to find the best balance: | |
| 257 | -too small means many background queries; too big means bigger messages | |
| 258 | -and too many unneeded rows returned (we picked 50 above for the sake of | |
| 259 | -example, but it's probably too small -- the default is 5000). | |
| 260 | - | |
| 261 | -Again, offset queries are inefficient by nature. Emulating them | |
| 262 | -client-side is a compromise when you think you can get away with the | |
| 263 | -performance hit. We recommend that you: | |
| 264 | - | |
| 265 | -* test your code at scale with the expected query patterns, to make sure | |
| 266 | - that your assumptions are correct; | |
| 267 | -* set a hard limit on the highest possible page number, to prevent | |
| 268 | - malicious users from triggering queries that would skip a huge amount | |
| 269 | - of rows. |
deleted features/pooling/README.md +0 −290
| @@ -1,290 +0,0 @@ | ||
| 1 | -## Connection pooling | |
| 2 | - | |
| 3 | -### Basics | |
| 4 | - | |
| 5 | -The driver communicates with Cassandra over TCP, using the Cassandra | |
| 6 | -binary protocol. This protocol is asynchronous, which allows each TCP | |
| 7 | -connection to handle multiple simultaneous requests: | |
| 8 | - | |
| 9 | -* when a query gets executed, a *stream id* gets assigned to it. It is a | |
| 10 | - unique identifier on the current connection; | |
| 11 | -* the driver writes a request containing the stream id and the query on | |
| 12 | - the connection, and then proceeds without waiting for the response (if | |
| 13 | - you're using the asynchronous API, this is when the driver will send you | |
| 14 | - back a [ResultSetFuture][result_set_future]). | |
| 15 | - Once the request has been written to the | |
| 16 | - connection, we say that it is *in flight*; | |
| 17 | -* at some point, Cassandra will send back a response on the connection. | |
| 18 | - This response also contains the stream id, which allows the driver to | |
| 19 | - trigger a callback that will complete the corresponding query (this is | |
| 20 | - the point where your `ResultSetFuture` will get completed). | |
| 21 | - | |
| 22 | -To increase the number of concurrent requests, we use a pool of | |
| 23 | -connections to each host. **For each `Session` object, there is one | |
| 24 | -connection pool per connected host**. | |
| 25 | - | |
| 26 | -The number of connections per pool is configurable (this will be | |
| 27 | -described in the next section). The number of stream ids depends on the | |
| 28 | -[native protocol version](../native_protocol/): | |
| 29 | - | |
| 30 | -* protocol v2 or below: 128 stream ids per connection. | |
| 31 | -* protocol v3 or above: up to 32768 stream ids per connection. | |
| 32 | - | |
| 33 | -```ditaa | |
| 34 | -+-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+ | |
| 35 | -|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+ | |
| 36 | -+-------+ +-------+ +----+ +----------+ +-------+ | |
| 37 | -``` | |
| 38 | - | |
| 39 | -### Configuring the connection pool | |
| 40 | - | |
| 41 | -Connections pools are configured with a [PoolingOptions][pooling_options] object, which | |
| 42 | -is global to a `Cluster` instance. You can pass that object when | |
| 43 | -building the cluster: | |
| 44 | - | |
| 45 | -```java | |
| 46 | -PoolingOptions poolingOptions = new PoolingOptions(); | |
| 47 | -// customize options... | |
| 48 | - | |
| 49 | -Cluster cluster = Cluster.builder() | |
| 50 | - .withContactPoints("127.0.0.1") | |
| 51 | - .withPoolingOptions(poolingOptions) | |
| 52 | - .build(); | |
| 53 | -``` | |
| 54 | - | |
| 55 | -Most options can also be changed at runtime. If you don't have a | |
| 56 | -reference to the `PoolingOptions` instance, here's how you can get it: | |
| 57 | - | |
| 58 | -```java | |
| 59 | -PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); | |
| 60 | -// customize options... | |
| 61 | -``` | |
| 62 | - | |
| 63 | -#### Pool size | |
| 64 | - | |
| 65 | -Connection pools have a variable size, which gets adjusted automatically | |
| 66 | -depending on the current load. There will always be at least a *core* | |
| 67 | -number of connections, and at most a *max* number. These values can be | |
| 68 | -configured independently by host *distance* (the distance is determined | |
| 69 | -by your [LoadBalancingPolicy][lbp], and will generally indicate whether a | |
| 70 | -host is in the same datacenter or not). | |
| 71 | - | |
| 72 | -```java | |
| 73 | -poolingOptions | |
| 74 | - .setCoreConnectionsPerHost(HostDistance.LOCAL, 4) | |
| 75 | - .setMaxConnectionsPerHost( HostDistance.LOCAL, 10) | |
| 76 | - .setCoreConnectionsPerHost(HostDistance.REMOTE, 2) | |
| 77 | - .setMaxConnectionsPerHost( HostDistance.REMOTE, 4); | |
| 78 | -``` | |
| 79 | - | |
| 80 | -For convenience, core and max can be set simultaneously: | |
| 81 | - | |
| 82 | -```java | |
| 83 | -poolingOptions | |
| 84 | - .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) | |
| 85 | - .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); | |
| 86 | -``` | |
| 87 | - | |
| 88 | -The default settings are: | |
| 89 | - | |
| 90 | -* protocol v2: | |
| 91 | - * `LOCAL` hosts: core = 2, max = 8 | |
| 92 | - * `REMOTE` hosts: core = 1, max = 2 | |
| 93 | -* protocol v3: | |
| 94 | - * `LOCAL` hosts: core = max = 1 | |
| 95 | - * `REMOTE` hosts: core = max = 1 | |
| 96 | - | |
| 97 | -[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold | |
| 98 | -that triggers the creation of a new connection when the pool is not at | |
| 99 | -its maximum capacity. In general, you shouldn't need to change its | |
| 100 | -default value. | |
| 101 | - | |
| 102 | -#### Dynamic resizing | |
| 103 | - | |
| 104 | -If core != max, the pool will resize automatically to adjust to the | |
| 105 | -current activity on the host. | |
| 106 | - | |
| 107 | -When activity goes up and there are *n* connections with n < max, the driver | |
| 108 | -will add a connection when the number of concurrent requests is more than | |
| 109 | -(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct] | |
| 110 | -(in layman's terms, when all but the last connection are full and the last | |
| 111 | -connection is above the threshold). | |
| 112 | - | |
| 113 | -When activity goes down, the driver will "trash" connections if the maximum | |
| 114 | -number of requests in a 10 second time period can be satisfied by less than | |
| 115 | -the number of connections opened. Trashed connections are kept open but do | |
| 116 | -not accept new requests. After a given timeout (defined by | |
| 117 | -[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed | |
| 118 | -and removed. If during that idle period activity increases again, those | |
| 119 | -connections will be resurrected back into the active pool and reused. The | |
| 120 | -main intent of that is to not constantly recreate connections if activity | |
| 121 | -changes quickly over an interval. | |
| 122 | - | |
| 123 | -#### Simultaneous requests per connection | |
| 124 | - | |
| 125 | -[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to | |
| 126 | -throttle the number of concurrent requests per connection. | |
| 127 | - | |
| 128 | -With protocol v2, there is no reason to throttle. It is set to 128 (the | |
| 129 | -max) and you should not change it. | |
| 130 | - | |
| 131 | -With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for | |
| 132 | -`REMOTE` hosts. These low defaults were chosen so that the default | |
| 133 | -configuration for protocol v2 and v3 allow the same total number of | |
| 134 | -simultaneous requests (to avoid bad surprises when clients migrate from | |
| 135 | -v2 to v3). You can raise this threshold, or even set it to the max: | |
| 136 | - | |
| 137 | -```java | |
| 138 | -poolingOptions | |
| 139 | - .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768) | |
| 140 | - .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000); | |
| 141 | -``` | |
| 142 | - | |
| 143 | -Just keep in mind that high values will give clients more bandwidth and | |
| 144 | -therefore put more pressure on your cluster. This might require some | |
| 145 | -tuning, especially if you have many clients. | |
| 146 | - | |
| 147 | -#### Heartbeat | |
| 148 | - | |
| 149 | -If connections stay idle for too long, they might be dropped by | |
| 150 | -intermediate network devices (routers, firewalls...). Normally, TCP | |
| 151 | -keepalive should take care of this; but tweaking low-level keepalive | |
| 152 | -settings might be impractical in some environments. | |
| 153 | - | |
| 154 | -The driver provides application-side keepalive in the form of a | |
| 155 | -connection heartbeat: when a connection has been idle for a given amount | |
| 156 | -of time, the driver will simulate activity by writing a dummy request to | |
| 157 | -it. | |
| 158 | - | |
| 159 | -This feature is enabled by default. The default heartbeat interval is 30 | |
| 160 | -seconds, it can be customized with the following method: | |
| 161 | - | |
| 162 | -```java | |
| 163 | -poolingOptions.setHeartbeatIntervalSeconds(60); | |
| 164 | -``` | |
| 165 | - | |
| 166 | -If it gets changed at runtime, only connections created after that will | |
| 167 | -use the new interval. Most users will want to do this at startup. | |
| 168 | - | |
| 169 | -The heartbeat interval should be set higher than | |
| 170 | -[SocketOptions.readTimeoutMillis][rtm]: | |
| 171 | -the read timeout is the maximum time that the driver waits for a regular | |
| 172 | -query to complete, therefore the connection should not be considered | |
| 173 | -idle before it has elapsed. | |
| 174 | - | |
| 175 | -To disable heartbeat, set the interval to 0. | |
| 176 | - | |
| 177 | -Implementation note: the dummy request sent by heartbeat is an | |
| 178 | -[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278) | |
| 179 | -message. | |
| 180 | - | |
| 181 | - | |
| 182 | -#### Acquisition timeout | |
| 183 | - | |
| 184 | -When the driver tries to send a request to a host, it will first try to | |
| 185 | -acquire a connection from this host's pool. If the pool is busy (i.e. | |
| 186 | -all connections are already handling their maximum number of in flight | |
| 187 | -requests), the client thread will block for a while, until a connection | |
| 188 | -becomes available (note that this will block even if you're using the | |
| 189 | -asynchronous API, like [Session.executeAsync][exec_async]). | |
| 190 | - | |
| 191 | -The time that the driver blocks is controlled by | |
| 192 | -[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection | |
| 193 | -available after this timeout, the driver will try the next host. | |
| 194 | - | |
| 195 | -For some applications, blocking is not acceptable, and it is preferable | |
| 196 | -to fail fast if the request cannot be fulfilled. If that's your case, | |
| 197 | -set the pool timeout to 0. If all hosts are busy, you will get a | |
| 198 | -[NoHostAvailableException][nhae] (if you look at the exception's details, you | |
| 199 | -will see a `java.util.concurrent.TimeoutException` for each host). | |
| 200 | - | |
| 201 | - | |
| 202 | -### Monitoring and tuning the pool | |
| 203 | - | |
| 204 | -The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's | |
| 205 | -a simple example that will print the number of open connections, active | |
| 206 | -requests, and maximum capacity for each host, every 5 seconds: | |
| 207 | - | |
| 208 | -```java | |
| 209 | -final LoadBalancingPolicy loadBalancingPolicy = | |
| 210 | - cluster.getConfiguration().getPolicies().getLoadBalancingPolicy(); | |
| 211 | -final PoolingOptions poolingOptions = | |
| 212 | -cluster.getConfiguration().getPoolingOptions(); | |
| 213 | - | |
| 214 | -ScheduledExecutorService scheduled = | |
| 215 | -Executors.newScheduledThreadPool(1); | |
| 216 | -scheduled.scheduleAtFixedRate(new Runnable() { | |
| 217 | - @Override | |
| 218 | - public void run() { | |
| 219 | - Session.State state = session.getState(); | |
| 220 | - for (Host host : state.getConnectedHosts()) { | |
| 221 | - HostDistance distance = loadBalancingPolicy.distance(host); | |
| 222 | - int connections = state.getOpenConnections(host); | |
| 223 | - int inFlightQueries = state.getInFlightQueries(host); | |
| 224 | - System.out.printf("%s connections=%d, current load=%d, max | |
| 225 | -load=%d%n", | |
| 226 | - host, connections, inFlightQueries, | |
| 227 | - connections * | |
| 228 | -poolingOptions.getMaxRequestsPerConnection(distance)); | |
| 229 | - } | |
| 230 | - } | |
| 231 | -}, 5, 5, TimeUnit.SECONDS); | |
| 232 | -``` | |
| 233 | - | |
| 234 | -In real life, you'll probably want something more sophisticated, like | |
| 235 | -exposing a JMX MBean or sending the data to your favorite monitoring | |
| 236 | -tool. | |
| 237 | - | |
| 238 | -If you find that the current load stays close or equal to the maximum | |
| 239 | -load at all time, it's a sign that your connection pools are saturated | |
| 240 | -and you should raise the max connections per host, or max requests per | |
| 241 | -connection (protocol v3). | |
| 242 | - | |
| 243 | -If you're using protocol v2 and the load is often less than core * 128, | |
| 244 | -your pools are underused and you could get away with less core | |
| 245 | -connections. | |
| 246 | - | |
| 247 | -#### Tuning protocol v3 for very high throughputs | |
| 248 | - | |
| 249 | -As mentioned above, the default pool size for protocol v3 is core = max | |
| 250 | -= 1. This means all requests to a given node will share a single | |
| 251 | -connection, and therefore a single Netty I/O thread. | |
| 252 | - | |
| 253 | -There is a corner case where this I/O thread can max out its CPU core | |
| 254 | -and become a bottleneck in the driver; in our benchmarks, this happened | |
| 255 | -with a single-node cluster and a high throughput (approximately 80K | |
| 256 | -requests / second). | |
| 257 | - | |
| 258 | -It's unlikely that you'll run into this issue: in most real-world | |
| 259 | -deployments, the driver connects to more than one node, so the load will | |
| 260 | -spread across more I/O threads. However if you suspect that you | |
| 261 | -experience the issue, here's what to look out for: | |
| 262 | - | |
| 263 | -* the driver throughput plateaus but the process does not appear to | |
| 264 | - max out any system resource (in particular, overall CPU usage is well | |
| 265 | - below 100%); | |
| 266 | -* one of the driver's I/O threads maxes out its CPU core. You can see | |
| 267 | - that with a profiler, or OS-level tools like `pidstat -tu` on Linux. | |
| 268 | - I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're | |
| 269 | - injecting your own `EventLoopGroup` with `NettyOptions`. | |
| 270 | - | |
| 271 | -The solution is to add more connections per node. To ensure that | |
| 272 | -additional connections get created before you run into the bottleneck, | |
| 273 | -either: | |
| 274 | - | |
| 275 | -* set core = max; | |
| 276 | -* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and | |
| 277 | - [newConnectionThreshold][nct] so that enough connections are added by | |
| 278 | - the time you reach the bottleneck. | |
| 279 | - | |
| 280 | -[result_set_future]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSetFuture.html | |
| 281 | -[pooling_options]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html | |
| 282 | -[lbp]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 283 | -[nct]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int) | |
| 284 | -[mrpc]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int) | |
| 285 | -[sits]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int) | |
| 286 | -[rtm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis() | |
| 287 | -[exec_async]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement) | |
| 288 | -[ptm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 289 | -[nhae]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 290 | -[get_state]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#getState() |
deleted features/query_timestamps/README.md +0 −76
| @@ -1,76 +0,0 @@ | ||
| 1 | -## Query timestamps | |
| 2 | - | |
| 3 | -In Cassandra, each mutation has a microsecond-precision timestamp, which | |
| 4 | -is used to order operations relative to each other. | |
| 5 | - | |
| 6 | -There are various ways to assign it: | |
| 7 | - | |
| 8 | -### Server-side generation | |
| 9 | - | |
| 10 | -If the client does not specify any timestamp, the server will assign one | |
| 11 | -based on the time it receives the query. | |
| 12 | - | |
| 13 | -This can be a problem when the order of the writes matter: with unlucky | |
| 14 | -timing (different coordinators, network latency, etc.), two successive | |
| 15 | -requests from the same client might be processed in a different order | |
| 16 | -server-side, and end up with out-of-order timestamps. | |
| 17 | - | |
| 18 | -### CQL `USING TIMESTAMP` | |
| 19 | - | |
| 20 | -You can explicitly provide the timestamp in your CQL query: | |
| 21 | - | |
| 22 | -```java | |
| 23 | -session.execute("INSERT INTO my_table(c1, c2) values (1, 1) " + | |
| 24 | - "USING TIMESTAMP 1432815430948040"); | |
| 25 | -``` | |
| 26 | - | |
| 27 | -This solves the problems of server-side generation: the client has | |
| 28 | -control over the ordering of the statements it generates. On the other | |
| 29 | -hand, it puts the burden of generating timestamps on client code. | |
| 30 | - | |
| 31 | -### Client-side generation | |
| 32 | - | |
| 33 | -Starting with version 2.1.2 of the driver, and if [native | |
| 34 | -protocol](../native_protocol/) v3 or above is in use, a *default | |
| 35 | -timestamp* can be sent with each query. | |
| 36 | - | |
| 37 | -To enable this feature, provide an instance of [TimestampGenerator][tsg] | |
| 38 | -at initialization: | |
| 39 | - | |
| 40 | -```java | |
| 41 | -Cluster.builder().addContactPoint("127.0.0.1") | |
| 42 | - .withTimestampGenerator(new AtomicMonotonicTimestampGenerator()) | |
| 43 | - .build(); | |
| 44 | -``` | |
| 45 | - | |
| 46 | -The default is still server-side generation. So unless you explicitly | |
| 47 | -provide a generator, you get the same behavior as previous driver | |
| 48 | -versions. | |
| 49 | - | |
| 50 | -In addition, you can also override the default timestamp on a | |
| 51 | -per-statement basis: | |
| 52 | - | |
| 53 | -```java | |
| 54 | -Statement statement = new SimpleStatement( | |
| 55 | - "UPDATE users SET email = 'x@y.com' where id = 1"); | |
| 56 | -statement.setDefaultTimestamp(1234567890); | |
| 57 | -session.execute(statement); | |
| 58 | -``` | |
| 59 | - | |
| 60 | -[tsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TimestampGenerator.html | |
| 61 | - | |
| 62 | -### Summary | |
| 63 | - | |
| 64 | -As shown in the previous sections, there are multiple ways to provide a | |
| 65 | -timestamp, some of which overlap. The order of precedence is the | |
| 66 | -following: | |
| 67 | - | |
| 68 | -1. if there is a `USING TIMESTAMP` clause in the CQL string, use that | |
| 69 | - over anything else; | |
| 70 | -2. otherwise, if a default timestamp was set on the statement and is | |
| 71 | - different from `Long.MIN_VALUE`, use it; | |
| 72 | -3. otherwise, if a generator is specified, invoke it and use its result | |
| 73 | - if it is different from `Long.MIN_VALUE`; | |
| 74 | -4. otherwise, let the server assign the timestamp. | |
| 75 | - | |
| 76 | -Steps 2 and 3 only apply if native protocol v3 or above is in use. |
deleted features/shaded_jar/README.md +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -## Using the shaded JAR | |
| 2 | - | |
| 3 | -The default driver JAR depends on [Netty](http://netty.io/), which is | |
| 4 | -used internally for networking. | |
| 5 | - | |
| 6 | -This explicit dependency can be a problem if your application already | |
| 7 | -uses another Netty version. To avoid conflicts, we provide a "shaded" | |
| 8 | -version of the JAR, which bundles the Netty classes under a different | |
| 9 | -package name: | |
| 10 | - | |
| 11 | -```xml | |
| 12 | -<dependency> | |
| 13 | - <groupId>com.datastax.cassandra</groupId> | |
| 14 | - <artifactId>cassandra-driver-core</artifactId> | |
| 15 | - <version>2.1.9</version> | |
| 16 | - <classifier>shaded</classifier> | |
| 17 | - <!-- Because the shaded JAR uses the original POM, you still need | |
| 18 | - to exclude this dependency explicitly: --> | |
| 19 | - <exclusions> | |
| 20 | - <exclusion> | |
| 21 | - <groupId>io.netty</groupId> | |
| 22 | - <artifactId>*</artifactId> | |
| 23 | - </exclusion> | |
| 24 | - </exclusions> | |
| 25 | -</dependency> | |
| 26 | -``` | |
| 27 | - | |
| 28 | -If you also use the mapper, you need to remove its dependency to the | |
| 29 | -non-shaded JAR: | |
| 30 | - | |
| 31 | -```xml | |
| 32 | -<dependency> | |
| 33 | - <groupId>com.datastax.cassandra</groupId> | |
| 34 | - <artifactId>cassandra-driver-core</artifactId> | |
| 35 | - <version>2.1.9</version> | |
| 36 | - <classifier>shaded</classifier> | |
| 37 | - <exclusions> | |
| 38 | - <exclusion> | |
| 39 | - <groupId>io.netty</groupId> | |
| 40 | - <artifactId>*</artifactId> | |
| 41 | - </exclusion> | |
| 42 | - </exclusions> | |
| 43 | -</dependency> | |
| 44 | -<dependency> | |
| 45 | - <groupId>com.datastax.cassandra</groupId> | |
| 46 | - <artifactId>cassandra-driver-mapping</artifactId> | |
| 47 | - <version>2.1.9</version> | |
| 48 | - <exclusions> | |
| 49 | - <exclusion> | |
| 50 | - <groupId>com.datastax.cassandra</groupId> | |
| 51 | - <artifactId>cassandra-driver-core</artifactId> | |
| 52 | - </exclusion> | |
| 53 | - </exclusions> | |
| 54 | -</dependency> | |
| 55 | -``` |
deleted features/speculative_execution/README.md +0 −343
| @@ -1,343 +0,0 @@ | ||
| 1 | -## Speculative query execution | |
| 2 | - | |
| 3 | -Sometimes a Cassandra node might be experiencing difficulties (ex: long | |
| 4 | -GC pause) and take longer than usual to reply. Queries sent to that node | |
| 5 | -will experience bad latency. | |
| 6 | - | |
| 7 | -One thing we can do to improve that is pre-emptively start a second | |
| 8 | -execution of the query against another node, before the first node has | |
| 9 | -replied or errored out. If that second node replies faster, we can send | |
| 10 | -the response back to the client (we also cancel the first query): | |
| 11 | - | |
| 12 | -```ditaa | |
| 13 | -client driver exec1 exec2 | |
| 14 | ---+----------------+--------------+------+--- | |
| 15 | - | execute(query) | | |
| 16 | - |--------------->| | |
| 17 | - | | query host1 | |
| 18 | - | |------------->| | |
| 19 | - | | | | |
| 20 | - | | | | |
| 21 | - | | query host2 | |
| 22 | - | |-------------------->| | |
| 23 | - | | | | | |
| 24 | - | | | | | |
| 25 | - | | host2 replies | | |
| 26 | - | |<--------------------| | |
| 27 | - | complete | | | |
| 28 | - |<---------------| | | |
| 29 | - | | cancel | | |
| 30 | - | |------------->| | |
| 31 | -``` | |
| 32 | - | |
| 33 | -Or the first node could reply just after the second execution was | |
| 34 | -started. In this case, we cancel the second execution. In other words, | |
| 35 | -whichever node replies faster "wins" and completes the client query: | |
| 36 | - | |
| 37 | -```ditaa | |
| 38 | -client driver exec1 exec2 | |
| 39 | ---+----------------+--------------+------+--- | |
| 40 | - | execute(query) | | |
| 41 | - |--------------->| | |
| 42 | - | | query host1 | |
| 43 | - | |------------->| | |
| 44 | - | | | | |
| 45 | - | | | | |
| 46 | - | | query host2 | |
| 47 | - | |-------------------->| | |
| 48 | - | | | | | |
| 49 | - | | | | | |
| 50 | - | | host1 replies| | | |
| 51 | - | |<-------------| | | |
| 52 | - | complete | | | |
| 53 | - |<---------------| | | |
| 54 | - | | cancel | | |
| 55 | - | |-------------------->| | |
| 56 | -``` | |
| 57 | - | |
| 58 | -Speculative executions are **disabled** by default. The following | |
| 59 | -sections cover the practical details and how to enable them. | |
| 60 | - | |
| 61 | -### Query idempotence | |
| 62 | - | |
| 63 | -One important aspect to consider is whether queries are idempotent, i.e. | |
| 64 | -whether they can be applied multiple times without changing the result | |
| 65 | -beyond the initial application. **If a query is not idempotent, the | |
| 66 | -driver will never schedule speculative executions for it**, because | |
| 67 | -there is no way to guarantee that only one node will apply the mutation. | |
| 68 | - | |
| 69 | -As of Cassandra 2.1.4, the only queries that are *not* idempotent are: | |
| 70 | - | |
| 71 | -* counter operations; | |
| 72 | -* prepending or appending to a list column; | |
| 73 | -* using non-idempotent CQL functions, like `now()` or `uuid()`. | |
| 74 | - | |
| 75 | -In the driver, this is determined by | |
| 76 | -[Statement#isIdempotent()][isIdempotent]. Unfortunately, the driver | |
| 77 | -doesn't parse query strings, so in most cases it has no information | |
| 78 | -about what the query actually does. Therefore: | |
| 79 | - | |
| 80 | -* **`Statement#isIdempotent()` is only computed automatically for | |
| 81 | - statements built with [QueryBuilder][QueryBuilder]**. | |
| 82 | - Note that the driver takes a rather conservative approach with uses | |
| 83 | - of `fcall()` or `raw()`: whenever they appear in a value to be | |
| 84 | - inserted in the database (like the values of an `Insert` or the | |
| 85 | - right-hand side of an assignment in an `Update`), the statement | |
| 86 | - will be considered non-idempotent by default. If you know that your | |
| 87 | - CQL functions or expressions are safe, force idempotence to `true` | |
| 88 | - on the statement manually (see below); | |
| 89 | -* **for all other types of statements, it defaults to `false`.** You'll | |
| 90 | - need to set it manually, with one of the mechanism described below. | |
| 91 | - | |
| 92 | -You can override the value on each statement: | |
| 93 | - | |
| 94 | -```java | |
| 95 | -Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 96 | -s.setIdempotent(true); | |
| 97 | -``` | |
| 98 | - | |
| 99 | -Note that this will also work for built statements (and override the | |
| 100 | -computed value). | |
| 101 | - | |
| 102 | -Additionally, if you know for a fact that your application does not use | |
| 103 | -any of the non-idempotent CQL queries listed above, you can change the | |
| 104 | -default cluster-wide: | |
| 105 | - | |
| 106 | -```java | |
| 107 | -// Make all statements idempotent by default: | |
| 108 | -cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true); | |
| 109 | -``` | |
| 110 | - | |
| 111 | -[isIdempotent]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html#isIdempotent() | |
| 112 | -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 113 | - | |
| 114 | -### Enabling speculative executions | |
| 115 | - | |
| 116 | -Speculative executions are controlled by an instance of | |
| 117 | -[SpeculativeExecutionPolicy][sep] provided when initializing the | |
| 118 | -`Cluster`. This policy defines the threshold after which a new | |
| 119 | -speculative execution will be triggered. | |
| 120 | - | |
| 121 | -[sep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html | |
| 122 | - | |
| 123 | -Two implementations are provided with the driver: | |
| 124 | - | |
| 125 | -#### [ConstantSpeculativeExecutionPolicy][csep] | |
| 126 | - | |
| 127 | -This simple policy uses a constant threshold: | |
| 128 | - | |
| 129 | -```java | |
| 130 | -Cluster cluster = Cluster.builder() | |
| 131 | - .addContactPoint("127.0.0.1") | |
| 132 | - .withSpeculativeExecutionPolicy( | |
| 133 | - new ConstantSpeculativeExecutionPolicy( | |
| 134 | - 500, // delay before a new execution is launched | |
| 135 | - 2 // maximum number of executions | |
| 136 | - )) | |
| 137 | - .build(); | |
| 138 | -``` | |
| 139 | - | |
| 140 | -Given the above configuration, an idempotent query would be handled this | |
| 141 | -way: | |
| 142 | - | |
| 143 | -* start the initial execution at t0; | |
| 144 | -* if no response has been received at t0 + 500 milliseconds, start a | |
| 145 | - speculative execution on another node; | |
| 146 | -* if no response has been received at t0 + 1000 milliseconds, start | |
| 147 | - another speculative execution on a third node. | |
| 148 | - | |
| 149 | -[csep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html | |
| 150 | - | |
| 151 | -#### [PercentileSpeculativeExecutionPolicy][psep] | |
| 152 | - | |
| 153 | -This policy sets the threshold at a given latency percentile for the | |
| 154 | -current host, based on recent statistics. | |
| 155 | - | |
| 156 | -**As of 2.1.6, this class is provided as a beta preview: it hasn't been | |
| 157 | -extensively tested yet, and the API is still subject to change.** | |
| 158 | - | |
| 159 | -First and foremost, make sure that the [HdrHistogram][hdr] library (used | |
| 160 | -under the hood to collect latencies) is in your classpath. It's defined | |
| 161 | -as an optional dependency in the driver's POM, so you'll need to | |
| 162 | -explicitly depend on it: | |
| 163 | - | |
| 164 | -```xml | |
| 165 | -<dependency> | |
| 166 | - <groupId>org.hdrhistogram</groupId> | |
| 167 | - <artifactId>HdrHistogram</artifactId> | |
| 168 | - <version>2.1.4</version> | |
| 169 | -</dependency> | |
| 170 | -``` | |
| 171 | - | |
| 172 | -Then create an instance of [PerHostPercentileTracker][phpt] that will collect | |
| 173 | -latency statistics for your `Cluster`: | |
| 174 | - | |
| 175 | -```java | |
| 176 | -// There are more options than shown here, please refer to the API docs | |
| 177 | -// for more information | |
| 178 | -PerHostPercentileTracker tracker = PerHostPercentileTracker | |
| 179 | - .builderWithHighestTrackableLatencyMillis(15000) | |
| 180 | - .build(); | |
| 181 | -``` | |
| 182 | - | |
| 183 | -Create an instance of the policy with the tracker, and pass it to your | |
| 184 | -cluster: | |
| 185 | - | |
| 186 | -```java | |
| 187 | -PercentileSpeculativeExecutionPolicy policy = | |
| 188 | - new PercentileSpeculativeExecutionPolicy( | |
| 189 | - tracker, | |
| 190 | - 99.0, // percentile | |
| 191 | - 2); // maximum number of executions | |
| 192 | - | |
| 193 | -Cluster cluster = Cluster.builder() | |
| 194 | - .addContactPoint("127.0.0.1") | |
| 195 | - .withSpeculativeExecutionPolicy(policy) | |
| 196 | - .build(); | |
| 197 | -``` | |
| 198 | - | |
| 199 | -Finally, don't forget to register your tracker with the cluster (the | |
| 200 | -policy does not do this itself): | |
| 201 | - | |
| 202 | -```java | |
| 203 | -cluster.register(tracker); | |
| 204 | -``` | |
| 205 | - | |
| 206 | -Note that `PerHostPercentileTracker` may also be used with a slow query | |
| 207 | -logger (see the [Logging](../logging/) section). In that case, you would | |
| 208 | -create a single tracker object and share it with both components. | |
| 209 | - | |
| 210 | -[psep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html | |
| 211 | -[hdr]: http://hdrhistogram.github.io/HdrHistogram/ | |
| 212 | -[phpt]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PerHostPercentileTracker.html | |
| 213 | - | |
| 214 | -#### Using your own | |
| 215 | - | |
| 216 | -As with all policies, you are free to provide your own by implementing | |
| 217 | -`SpeculativeExecutionPolicy`. | |
| 218 | - | |
| 219 | -### How speculative executions affect retries | |
| 220 | - | |
| 221 | -Regardless of speculative executions, the driver has a retry mechanism: | |
| 222 | - | |
| 223 | -* on an internal error, it will try the next host; | |
| 224 | -* when the consistency level could not be reached (`unavailable` error | |
| 225 | - or read or write timeout), it will delegate the decision to | |
| 226 | - [RetryPolicy][retry_policy], which might trigger a retry on the same | |
| 227 | - host. | |
| 228 | - | |
| 229 | -Turning speculative executions on doesn't change this behavior. Each | |
| 230 | -parallel execution will trigger retries independently: | |
| 231 | - | |
| 232 | -```ditaa | |
| 233 | -client driver exec1 exec2 | |
| 234 | ---+----------------+--------------+------+--- | |
| 235 | - | execute(query) | | |
| 236 | - |--------------->| | |
| 237 | - | | query host1 | |
| 238 | - | |------------->| | |
| 239 | - | | | | |
| 240 | - | | unavailable | | |
| 241 | - | |<-------------| | |
| 242 | - | | | |
| 243 | - | |retry at lower CL | |
| 244 | - | |------------->| | |
| 245 | - | | | | |
| 246 | - | | query host2 | |
| 247 | - | |-------------------->| | |
| 248 | - | | | | | |
| 249 | - | | server error | | |
| 250 | - | |<--------------------| | |
| 251 | - | | | | |
| 252 | - | | retry on host3 | |
| 253 | - | |-------------------->| | |
| 254 | - | | | | | |
| 255 | - | | host1 replies| | | |
| 256 | - | |<-------------| | | |
| 257 | - | complete | | | |
| 258 | - |<---------------| | | |
| 259 | - | | cancel | | |
| 260 | - | |-------------------->| | |
| 261 | -``` | |
| 262 | - | |
| 263 | -The only impact is that all executions of the same query always share | |
| 264 | -the same query plan, so each host will be used by at most one execution. | |
| 265 | - | |
| 266 | -[retry_policy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html | |
| 267 | - | |
| 268 | -### Tuning and practical details | |
| 269 | - | |
| 270 | -The goal of speculative executions is to improve overall latency (the | |
| 271 | -time between `execute(query)` and `complete` in the diagrams above) at | |
| 272 | -high percentiles. On the flipside, they cause the driver to send more | |
| 273 | -individual requests, so throughput will not necessarily improve. | |
| 274 | - | |
| 275 | -You can monitor how many speculative executions were triggered with the | |
| 276 | -`speculative-executions` metric (exposed in the Java API as | |
| 277 | -[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]). | |
| 278 | -It should only be a few percents of the total number of requests | |
| 279 | -([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]). | |
| 280 | - | |
| 281 | -[se_metric]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions() | |
| 282 | -[request_metric]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metrics.html#getRequestsTimer() | |
| 283 | - | |
| 284 | -#### Stream id exhaustion | |
| 285 | - | |
| 286 | -One side-effect of speculative executions is that many requests are | |
| 287 | -cancelled, which can lead to a phenomenon called *stream id exhaustion*: | |
| 288 | -each TCP connection can handle multiple simultaneous requests, | |
| 289 | -identified by a unique number called *stream id*. When a request gets | |
| 290 | -cancelled, we can't reuse its stream id immediately because we might | |
| 291 | -still receive a response from the server later. If this happens often, | |
| 292 | -the number of available stream ids diminishes over time, and when it | |
| 293 | -goes below a given threshold we close the connection and create a new | |
| 294 | -one. If requests are often cancelled, so will see connections being | |
| 295 | -recycled at a high rate. | |
| 296 | - | |
| 297 | -One way to detect this is to monitor open connections per host | |
| 298 | -([Session.getState().getOpenConnections(host)][session_state]) against | |
| 299 | -TCP connections at the OS level. If open connections stay constant but | |
| 300 | -you see many TCP connections in closing states, you might be running | |
| 301 | -into this issue. Try raising the speculative execution threshold. | |
| 302 | - | |
| 303 | -This problem is more likely to happen with version 2 of the native | |
| 304 | -protocol, because each TCP connection only has 128 stream ids. With | |
| 305 | -version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are | |
| 306 | -32K stream ids per connection, so higher cancellation rates can be | |
| 307 | -sustained. If you're unsure of which native protocol version you're | |
| 308 | -using, you can check with | |
| 309 | -[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version]. | |
| 310 | - | |
| 311 | -[session_state]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.State.html | |
| 312 | -[protocol_version]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion() | |
| 313 | - | |
| 314 | -#### Request ordering and client timestamps | |
| 315 | - | |
| 316 | -Another issue that might arise is that you get unintuitive results | |
| 317 | -because of request ordering. Suppose you run the following query with | |
| 318 | -speculative executions enabled: | |
| 319 | - | |
| 320 | - insert into my_table (k, v) values (1, 1); | |
| 321 | - | |
| 322 | -The first execution is a bit too slow, so a second execution gets | |
| 323 | -triggered. Finally, the first execution completes, so the client code | |
| 324 | -gets back an acknowledgement, and the second execution is cancelled. | |
| 325 | -However, cancelling only means that the driver stops waiting for the | |
| 326 | -server's response, the request could still be "on the wire"; let's | |
| 327 | -assume that this is the case. | |
| 328 | - | |
| 329 | -Now you run the following query, which completes successfully: | |
| 330 | - | |
| 331 | - delete from my_table where k = 1; | |
| 332 | - | |
| 333 | -But now the second execution of the first query finally reaches its | |
| 334 | -target node, which applies the mutation. The row that you've just | |
| 335 | -deleted is back! | |
| 336 | - | |
| 337 | -The workaround is to use a timestamp with your queries: | |
| 338 | - | |
| 339 | - insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000; | |
| 340 | - | |
| 341 | -If you're using native protocol v3, you can also enable [client-side | |
| 342 | -timestamps](../query_timestamps/#client-side-generation) to have this done | |
| 343 | -automatically. |
deleted features/ssl/README.md +0 −180
| @@ -1,180 +0,0 @@ | ||
| 1 | -## SSL | |
| 2 | - | |
| 3 | -You can secure traffic between the driver and Cassandra with SSL. There | |
| 4 | -are two aspects to that: | |
| 5 | - | |
| 6 | -* **client-to-node encryption**, where the traffic is encrypted, and the | |
| 7 | - client verifies the identity of the Cassandra nodes it connects to; | |
| 8 | -* optionally, **client certificate authentication**, where Cassandra | |
| 9 | - nodes also verify the identity of the client. | |
| 10 | - | |
| 11 | -This section describes the driver-side configuration; it assumes that | |
| 12 | -you've already configured SSL in Cassandra: | |
| 13 | - | |
| 14 | -* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html) | |
| 15 | - covers a basic approach with self-signed certificates, which is fine | |
| 16 | - for development and tests. | |
| 17 | -* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html) | |
| 18 | - details a more advanced solution based on a Certificate Authority | |
| 19 | - (CA). | |
| 20 | - | |
| 21 | -### Preparing the certificates | |
| 22 | - | |
| 23 | -#### Client truststore | |
| 24 | - | |
| 25 | -This is required for client-to-node encryption. | |
| 26 | - | |
| 27 | -If you're using self-signed certificates, you need to export the public | |
| 28 | -part of each node's certificate from that node's keystore: | |
| 29 | - | |
| 30 | -``` | |
| 31 | -keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore | |
| 32 | -``` | |
| 33 | - | |
| 34 | -Then add all public certificates to the client truststore: | |
| 35 | - | |
| 36 | -``` | |
| 37 | -keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore | |
| 38 | -keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore | |
| 39 | -... | |
| 40 | -``` | |
| 41 | - | |
| 42 | -If you're using a Certificate Authority, the client truststore only | |
| 43 | -needs to contain the CA's certificate: | |
| 44 | - | |
| 45 | -``` | |
| 46 | -keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore | |
| 47 | -``` | |
| 48 | - | |
| 49 | -#### Client keystore | |
| 50 | - | |
| 51 | -If you also intend to use client certificate authentication, generate | |
| 52 | -the public and private key pair for the client: | |
| 53 | - | |
| 54 | -``` | |
| 55 | -keytool -genkey -keyalg RSA -alias client -keystore client.keystore | |
| 56 | -``` | |
| 57 | - | |
| 58 | -If you're using self-signed certificates, extract the public part of the | |
| 59 | -client certificate, and import it in the truststore of each Cassandra | |
| 60 | -node: | |
| 61 | - | |
| 62 | -``` | |
| 63 | -keytool -export -alias client -file client.cer -keystore client.keystore | |
| 64 | -keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore | |
| 65 | -``` | |
| 66 | - | |
| 67 | -If you're using a CA, sign the client certificate with it (see the blog | |
| 68 | -post linked at the top of this page). Then the nodes' truststores only | |
| 69 | -need to contain the CA's certificate (which should already be the case | |
| 70 | -if you've followed the steps for inter-node encryption). | |
| 71 | - | |
| 72 | -### Driver configuration | |
| 73 | - | |
| 74 | -#### Property-based | |
| 75 | - | |
| 76 | -`withSSL()` gives you a basic JSSE configuration: | |
| 77 | - | |
| 78 | -```java | |
| 79 | -Cluster cluster = Cluster.builder() | |
| 80 | - .addContactPoint("127.0.0.1") | |
| 81 | - .withSSL() | |
| 82 | - .build(); | |
| 83 | -``` | |
| 84 | - | |
| 85 | -You can then use | |
| 86 | -[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization) | |
| 87 | -for specific details, like keystore locations and passwords: | |
| 88 | - | |
| 89 | -``` | |
| 90 | --Djavax.net.ssl.trustStore=/path/to/client.truststore | |
| 91 | --Djavax.net.ssl.trustStorePassword=password123 | |
| 92 | -# If you're using client authentication: | |
| 93 | --Djavax.net.ssl.keyStore=/path/to/client.keystore | |
| 94 | --Djavax.net.ssl.keyStorePassword=password123 | |
| 95 | -``` | |
| 96 | - | |
| 97 | -#### Programmatic | |
| 98 | - | |
| 99 | -If you need more control than what system properties allow, you can | |
| 100 | -configure SSL programmatically by creating an [SSLOptions] instance: | |
| 101 | - | |
| 102 | -```java | |
| 103 | -SSLContext sslContext = ... // create and configure SSL context | |
| 104 | -String[] cipherSuites = ... | |
| 105 | - | |
| 106 | -SSLOptions sslOptions = new SSLOptions(sslContext, cipherSuites); | |
| 107 | - | |
| 108 | -Cluster cluster = Cluster.builder() | |
| 109 | - .addContactPoint("127.0.0.1") | |
| 110 | - .withSSL(sslOptions) | |
| 111 | - .build(); | |
| 112 | -``` | |
| 113 | - | |
| 114 | -A known limitation of the current API is that you can't customize the | |
| 115 | -`SSLEngine`, which prevents advanced features like hostname | |
| 116 | -verification. This will be fixed in 3.0 (see | |
| 117 | -[JAVA-841](https://datastax-oss.atlassian.net/browse/JAVA-841)), in the | |
| 118 | -meantime see below for a workaround. | |
| 119 | - | |
| 120 | - | |
| 121 | -### Bypassing `SSLOptions` | |
| 122 | - | |
| 123 | -For advanced use cases, it's possible to bypass `SSLOptions` entirely: | |
| 124 | -since the driver provides a hook into the Netty pipeline (by way of | |
| 125 | -[NettyOptions]), you can add the SSL handler yourself: | |
| 126 | - | |
| 127 | -```java | |
| 128 | -import io.netty.handler.ssl.SslHandler; | |
| 129 | -import javax.net.ssl.SSLContext; | |
| 130 | -import javax.net.ssl.SSLEngine; | |
| 131 | - | |
| 132 | -// Base implementation: each time a connection is established, create an SSL handler | |
| 133 | -// and add it to the pipeline: | |
| 134 | -public abstract class SslNettyOptions extends NettyOptions { | |
| 135 | - @Override | |
| 136 | - public void afterChannelInitialized(SocketChannel channel) throws Exception { | |
| 137 | - channel.pipeline().addFirst("ssl", createSslHandler(channel)); | |
| 138 | - } | |
| 139 | - | |
| 140 | - protected abstract SslHandler createSslHandler(SocketChannel channel); | |
| 141 | -} | |
| 142 | - | |
| 143 | -// Concrete implementation based on JSSE | |
| 144 | -public class MyNettyOptions extends SslNettyOptions { | |
| 145 | - | |
| 146 | - private final SSLContext sslContext = createContext(); | |
| 147 | - | |
| 148 | - protected SslHandler createSslHandler(SocketChannel channel) { | |
| 149 | - return new SslHandler(createEngine(sslContext, channel)); | |
| 150 | - } | |
| 151 | - | |
| 152 | - private static SSLContext createContext() { | |
| 153 | - ... // create and configure context | |
| 154 | - } | |
| 155 | - | |
| 156 | - private static SSLEngine createEngine(SSLContext sslContext, SocketChannel channel) { | |
| 157 | - SSLEngine engine = sslContext.createSSLEngine(); | |
| 158 | - engine.setUseClientMode(true); | |
| 159 | - ... // any extra configuration | |
| 160 | - return engine; | |
| 161 | - } | |
| 162 | -} | |
| 163 | - | |
| 164 | -cluster = Cluster.builder() | |
| 165 | - .addContactPoint("127.0.0.1") | |
| 166 | - .withNettyOptions(new MyNettyOptions()) | |
| 167 | - .build(); | |
| 168 | -``` | |
| 169 | - | |
| 170 | -This could be used for the following use cases: | |
| 171 | - | |
| 172 | -* fine control over JSSE configuration, for example tuning the SSL | |
| 173 | - engine for hostname verification; | |
| 174 | -* bypassing JSSE altogether in favor of another SSL implementation: | |
| 175 | - recent Netty versions support | |
| 176 | - [OpenSSL](http://netty.io/wiki/forked-tomcat-native.html) | |
| 177 | - for improved performance. | |
| 178 | - | |
| 179 | -[SSLOptions]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SSLOptions.html | |
| 180 | -[NettyOptions]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/NettyOptions.html |
deleted features/statements/README.md +0 −54
| @@ -1,54 +0,0 @@ | ||
| 1 | -## Statements | |
| 2 | - | |
| 3 | -To execute a query, you create a [Statement] instance and pass it to | |
| 4 | -`Session#execute()`. The driver provides various implementations: | |
| 5 | - | |
| 6 | -* [SimpleStatement]: a simple implementation built directly from a | |
| 7 | - character string. Typically used for queries that are executed only | |
| 8 | - once or a few times. | |
| 9 | -* [BoundStatement]: obtained by binding values to a [prepared | |
| 10 | - statement](prepared/). Typically used for queries that are executed | |
| 11 | - often, with different values. | |
| 12 | -* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It | |
| 13 | - can be executed directly like a simple statement, or prepared. | |
| 14 | -* [BatchStatement]: a statement that groups multiple statements to be | |
| 15 | - executed as a batch. | |
| 16 | - | |
| 17 | -`Session` also has a shortcut to build and execute a simple statement in | |
| 18 | -a single call: | |
| 19 | - | |
| 20 | -```java | |
| 21 | -session.execute("select release_version from system.local"); | |
| 22 | - | |
| 23 | -// Is equivalent to: | |
| 24 | -Statement s = new SimpleStatement("select release_version from system.local"); | |
| 25 | -session.execute(s); | |
| 26 | -``` | |
| 27 | - | |
| 28 | -### Customizing execution | |
| 29 | - | |
| 30 | -Before executing a statement, you might want to customize certain | |
| 31 | -aspects of its execution. `Statement` provides a number of methods for | |
| 32 | -this, for example: | |
| 33 | - | |
| 34 | -```java | |
| 35 | -Statement s = new SimpleStatement("select release_version from system.local"); | |
| 36 | -s.enableTracing(); | |
| 37 | -session.execute(s); | |
| 38 | -``` | |
| 39 | - | |
| 40 | -If you use custom policies ([RetryPolicy], [LoadBalancingPolicy], | |
| 41 | -[SpeculativeExecutionPolicy]...), you might also want to have custom | |
| 42 | -properties that influence statement execution. To achieve this, you can | |
| 43 | -wrap your statements in a custom [StatementWrapper] implementation. | |
| 44 | - | |
| 45 | -[Statement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html | |
| 46 | -[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html | |
| 47 | -[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html | |
| 48 | -[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html | |
| 49 | -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 50 | -[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/BuiltStatement.html | |
| 51 | -[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/StatementWrapper.html | |
| 52 | -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html | |
| 53 | -[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 54 | -[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html |
deleted features/statements/prepared/README.md +0 −172
| @@ -1,172 +0,0 @@ | ||
| 1 | -## Prepared statements | |
| 2 | - | |
| 3 | -When Cassandra executes a query, the first thing it does is parse the | |
| 4 | -query string to an internal representation. If the same query is used | |
| 5 | -often, you can use a prepared statement, which allows Cassandra to cache | |
| 6 | -that representation, and save time and resources for subsequent | |
| 7 | -executions. Prepared statements are typically parameterized, using | |
| 8 | -different values for each execution: | |
| 9 | - | |
| 10 | -```java | |
| 11 | -PreparedStatement prepared = session.prepare( | |
| 12 | - "insert into product (sku, description) values (?, ?)"); | |
| 13 | - | |
| 14 | -BoundStatement bound; | |
| 15 | - | |
| 16 | -bound = prepared.bind("234827", "Mouse"); | |
| 17 | -session.execute(bound); | |
| 18 | - | |
| 19 | -bound = prepared.bind("987274", "Keyboard"); | |
| 20 | -session.execute(bound); | |
| 21 | -``` | |
| 22 | - | |
| 23 | -Statements should be be prepared only once. If you call `prepare` | |
| 24 | -multiple times with the same query string, the driver will log a | |
| 25 | -warning. So your application should cache the `PreparedStatement` object | |
| 26 | -once it's been created (this can be as simple as storing it as a field | |
| 27 | -in a DAO). | |
| 28 | - | |
| 29 | -### Parameters and binding | |
| 30 | - | |
| 31 | -Parameters can be either anonymous or named (named parameters are only | |
| 32 | -available with [native protocol](../../native_protocol) v2 or above): | |
| 33 | - | |
| 34 | -```java | |
| 35 | -ps1 = session.prepare("insert into product (sku, description) values (?, ?)"); | |
| 36 | -ps2 = session.prepare("insert into product (sku, description) values (:s, :d)"); | |
| 37 | -``` | |
| 38 | - | |
| 39 | -To turn the statement into its executable form, you need to *bind* it | |
| 40 | -and provide values for the parameters. As shown previously, there is a | |
| 41 | -shorthand form to do it all in one call: | |
| 42 | - | |
| 43 | -```java | |
| 44 | -BoundStatement bound = ps1.bind("324378", "LCD screen"); | |
| 45 | -``` | |
| 46 | - | |
| 47 | -You can also bind first, then use setters, which is slightly more | |
| 48 | -explicit: | |
| 49 | - | |
| 50 | -```java | |
| 51 | -// Positional setters: | |
| 52 | -BoundStatement bound = ps1.bind() | |
| 53 | - .setString(0, "324378") | |
| 54 | - .setString(1, "LCD screen"); | |
| 55 | - | |
| 56 | -// Named setters: | |
| 57 | -BoundStatement bound = ps2.bind() | |
| 58 | - .setString("s", "324378") | |
| 59 | - .setString("d", "LCD screen"); | |
| 60 | -``` | |
| 61 | - | |
| 62 | -If you don't set a parameter, it is sent as `null` (note that this | |
| 63 | -behavior changes in the 2.1 branch of the driver). | |
| 64 | - | |
| 65 | -You can use named setters even if the query uses anonymous parameters; | |
| 66 | -Cassandra will name the parameters after the column they apply to: | |
| 67 | - | |
| 68 | -```java | |
| 69 | -BoundStatement bound = ps1.bind() | |
| 70 | - .setString("sku", "324378") | |
| 71 | - .setString("description", "LCD screen"); | |
| 72 | -``` | |
| 73 | - | |
| 74 | -This can be ambiguous if the query uses the same column multiple times, | |
| 75 | -for example: `select * from sales where sku = ? and date > ? and date < | |
| 76 | -?`. In these situations, use positional setters or named parameters. | |
| 77 | - | |
| 78 | -A bound statement also has getters to retrieve the values. Note that | |
| 79 | -this has a small performance overhead since values are stored in their | |
| 80 | -serialized form. | |
| 81 | - | |
| 82 | -### How the driver handles prepared statements | |
| 83 | - | |
| 84 | -When the driver prepares a statement, it sends the query string to | |
| 85 | -Cassandra, which caches the statement and returns an identifier. Later, | |
| 86 | -when the driver needs to execute the statement, it just sends the | |
| 87 | -identifier and parameter values. Note that the identifier is | |
| 88 | -deterministic, so it will always be the same for all nodes (it's a | |
| 89 | -actually a hash of the query string). | |
| 90 | - | |
| 91 | -Prepared statements are not replicated across the cluster. It is the | |
| 92 | -driver's responsibility to ensure that each node's cache is up to | |
| 93 | -date. It uses a number of strategies to achieve this: | |
| 94 | - | |
| 95 | -1. When a statement is initially prepared, it is first sent to a single | |
| 96 | - node in the cluster (this prevents from hitting all nodes in case | |
| 97 | - the query string is wrong). Once that node replies successfully, the | |
| 98 | - driver re-prepares on all remaining nodes: | |
| 99 | - | |
| 100 | - ```ditaa | |
| 101 | - client driver node1 node2 node3 | |
| 102 | - --+------------------------+----------------+--------------+------+--- | |
| 103 | - | | | | | | |
| 104 | - | session.prepare(query) | | | | | |
| 105 | - |----------------------->| | | | | |
| 106 | - | | PREPARE(query) | | | | |
| 107 | - | |--------------->| | | | |
| 108 | - | | | | | | |
| 109 | - | | PREPARED(id) | | | | |
| 110 | - | |<---------------| | | | |
| 111 | - | | | | | | |
| 112 | - | | | | | | |
| 113 | - | | PREPARE(query) | | | |
| 114 | - | |------------------------------>| | | |
| 115 | - | | | | | | |
| 116 | - | | PREPARE(query) | | | |
| 117 | - | |------------------------------------->| | |
| 118 | - | | | | | | |
| 119 | - |<-----------------------| | | | | |
| 120 | - ``` | |
| 121 | - | |
| 122 | -2. if a node crashes, it loses all of its prepared statements. So the | |
| 123 | - driver keeps a client-side cache; anytime a node is marked back up, | |
| 124 | - the driver re-prepares all statements on it; | |
| 125 | - | |
| 126 | -3. finally, if the driver tries to execute a statement and finds out | |
| 127 | - that the coordinator doesn't know about it, it will re-prepare the | |
| 128 | - statement on the fly (this is transparent for the client, but will cost | |
| 129 | - two extra roundtrips): | |
| 130 | - | |
| 131 | - ```ditaa | |
| 132 | - client driver node1 | |
| 133 | - --+-------------------------------+------------------------------+-- | |
| 134 | - | | | | |
| 135 | - |session.execute(boundStatement)| | | |
| 136 | - +------------------------------>| | | |
| 137 | - | | EXECUTE(id, values) | | |
| 138 | - | |----------------------------->| | |
| 139 | - | | | | |
| 140 | - | | UNPREPARED | | |
| 141 | - | |<-----------------------------| | |
| 142 | - | | | | |
| 143 | - | | | | |
| 144 | - | | PREPARE(query) | | |
| 145 | - | |----------------------------->| | |
| 146 | - | | | | |
| 147 | - | | PREPARED(id) | | |
| 148 | - | |<-----------------------------| | |
| 149 | - | | | | |
| 150 | - | | | | |
| 151 | - | | EXECUTE(id, values) | | |
| 152 | - | |----------------------------->| | |
| 153 | - | | | | |
| 154 | - | | ROWS | | |
| 155 | - | |<-----------------------------| | |
| 156 | - | | | | |
| 157 | - |<------------------------------| | | |
| 158 | - ``` | |
| 159 | - | |
| 160 | -You can customize these strategies through `QueryOptions`: | |
| 161 | - | |
| 162 | -* [setPrepareOnAllHosts] controls whether statements are initially | |
| 163 | - re-prepared on other hosts (step 1 above); | |
| 164 | -* [setReprepareOnUp] controls whether statements are re-prepared on a | |
| 165 | - node that comes back up (step 2 above). | |
| 166 | - | |
| 167 | -Changing the driver's defaults should be done with care and only in | |
| 168 | -specific situations; read each method's Javadoc for detailed | |
| 169 | -explanations. | |
| 170 | - | |
| 171 | -[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean) | |
| 172 | -[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean) |
added manual/README.md +17 −0
| @@ -0,0 +1,17 @@ | ||
| 1 | +## Manual | |
| 2 | + | |
| 3 | +This part of the documentation is organized into sub-sections covering | |
| 4 | +specific topics. | |
| 5 | + | |
| 6 | +If you're reading this from the [generated HTML documentation on | |
| 7 | +github.io](http://datastax.github.io/java-driver/), use the "Read More" | |
| 8 | +menu on the right hand side. If you're [browsing the source files on | |
| 9 | +github.com](https://github.com/datastax/java-driver/tree/2.1/manual), | |
| 10 | +simply navigate to each sub-directory. | |
| 11 | + | |
| 12 | +This is a work in progress: new sections will be added to cover existing | |
| 13 | +features or document new ones. | |
| 14 | + | |
| 15 | +You can also find more help in the legacy | |
| 16 | +[user documentation](http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/whatsNew2.html) | |
| 17 | +on the DataStax website. |
added manual/address_resolution/README.md +67 −0
| @@ -0,0 +1,67 @@ | ||
| 1 | +## Address resolution | |
| 2 | + | |
| 3 | +The driver auto-detects new Cassandra nodes added to the cluster through server | |
| 4 | +side push notifications and through checking the system tables. | |
| 5 | + | |
| 6 | +For each node, the address the driver will receive will correspond to the address set as | |
| 7 | +`rpc_address` in the node's `cassandra.yaml` file. In most cases, this is the correct value. | |
| 8 | +However, sometimes the addresses received through this mechanism will either not be | |
| 9 | +reachable directly by the driver, or should not be the preferred address to use | |
| 10 | +(for instance, it might be a private IP, but some clients may have to use a public IP, or | |
| 11 | +go through a router). | |
| 12 | + | |
| 13 | +### The [AddressTranslater][at] interface | |
| 14 | + | |
| 15 | +This interface allows you to deal with such cases, by transforming the address sent by a | |
| 16 | +Cassandra node to another address to be used by the driver for connection. | |
| 17 | + | |
| 18 | +```java | |
| 19 | +public class MyAddressTranslater implements AddressTranslater { | |
| 20 | + public InetSocketAddress translate(InetSocketAddress address) { | |
| 21 | + ... // your custom translation logic | |
| 22 | + } | |
| 23 | +} | |
| 24 | + | |
| 25 | +Cluster cluster = Cluster.builder() | |
| 26 | + .addContactPoint("1.2.3.4") | |
| 27 | + .withAddressTranslater(new MyAddressTranslater()) | |
| 28 | + .build(); | |
| 29 | +``` | |
| 30 | + | |
| 31 | +Notes: | |
| 32 | + | |
| 33 | +* the contact points provided while creating the `Cluster` are not translated, only addresses | |
| 34 | + retrieved from or sent by Cassandra nodes are; | |
| 35 | +* you might want to implement [CloseableAddressTranslater][cat] if your | |
| 36 | + implementation has state that should be cleaned up when the `Cluster` | |
| 37 | + shuts down. This is provided as a separate interface for historical | |
| 38 | + reasons, the `close()` method will be merged in `AddressTranslater` in a | |
| 39 | + future release. | |
| 40 | + | |
| 41 | +[at]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/AddressTranslater.html | |
| 42 | +[cat]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/CloseableAddressTranslater.html | |
| 43 | + | |
| 44 | +### EC2 multi-region | |
| 45 | + | |
| 46 | +[EC2MultiRegionAddressTranslater][ec2] is provided out of the box. It | |
| 47 | +helps optimize network costs when your infrastructure (both Cassandra | |
| 48 | +nodes *and* clients) is distributed across multiple Amazon EC2 regions: | |
| 49 | + | |
| 50 | +* a client communicating with a Cassandra node *in the same EC2 region* should use the node's | |
| 51 | + private IP (which is less expensive); | |
| 52 | +* a client communicating with a node in a different region should use the public IP. | |
| 53 | + | |
| 54 | +To use this implementation, provide an instance when initializing the `Cluster`: | |
| 55 | + | |
| 56 | +```java | |
| 57 | +Cluster cluster = Cluster.builder() | |
| 58 | + .addContactPoint("1.2.3.4") | |
| 59 | + .withAddressTranslater(new EC2MultiRegionAddressTranslater()) | |
| 60 | + .build(); | |
| 61 | +``` | |
| 62 | + | |
| 63 | +This class performs a reverse DNS lookup of the origin address, to find the domain name of the | |
| 64 | +target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the | |
| 65 | +private/public switch automatically based on location. | |
| 66 | + | |
| 67 | +[ec2]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.html |
added manual/async/README.md +162 −0
| @@ -0,0 +1,162 @@ | ||
| 1 | +## Asynchronous programming | |
| 2 | + | |
| 3 | +The driver exposes an asynchronous API that allows you to write programs | |
| 4 | +in a fully-non blocking manner. Asynchronous methods return instances of | |
| 5 | +Guava's [ListenableFuture], that can be conveniently chained and | |
| 6 | +composed. | |
| 7 | + | |
| 8 | +Here is a short example that opens a session and runs a query | |
| 9 | +asynchronously: | |
| 10 | + | |
| 11 | +```java | |
| 12 | +import com.google.common.util.concurrent.*; | |
| 13 | + | |
| 14 | +ListenableFuture<Session> session = cluster.connectAsync(); | |
| 15 | + | |
| 16 | +// Use transform with an AsyncFunction to chain an async operation after another: | |
| 17 | +ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 18 | + new AsyncFunction<Session, ResultSet>() { | |
| 19 | + public ListenableFuture<ResultSet> apply(Session session) throws Exception { | |
| 20 | + return session.executeAsync("select release_version from system.local"); | |
| 21 | + } | |
| 22 | + }); | |
| 23 | + | |
| 24 | +// Use transform with a simple Function to apply a synchronous computation on the result: | |
| 25 | +ListenableFuture<String> version = Futures.transform(resultSet, | |
| 26 | + new Function<ResultSet, String>() { | |
| 27 | + public String apply(ResultSet rs) { | |
| 28 | + return rs.one().getString("release_version"); | |
| 29 | + } | |
| 30 | + }); | |
| 31 | + | |
| 32 | +// Use a callback to perform an action once the future is complete: | |
| 33 | +Futures.addCallback(version, new FutureCallback<String>() { | |
| 34 | + public void onSuccess(String version) { | |
| 35 | + System.out.printf("Cassandra version: %s%n", version); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public void onFailure(Throwable t) { | |
| 39 | + System.out.printf("Failed to retrieve the version: %s%n", | |
| 40 | + t.getMessage()); | |
| 41 | + } | |
| 42 | +}); | |
| 43 | +``` | |
| 44 | + | |
| 45 | +### Async paging | |
| 46 | + | |
| 47 | +If you consume a `ResultSet` in a callback, be aware that iterating the | |
| 48 | +rows will trigger synchronous queries as you page through the results. | |
| 49 | +To avoid this, use [getAvailableWithoutFetching] to limit the iteration | |
| 50 | +to the current page, and [fetchMoreResults] to get a future to the next | |
| 51 | +page (see also the section on [paging](../paging/)). | |
| 52 | +Here is a full example: | |
| 53 | + | |
| 54 | +[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching-- | |
| 55 | +[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#fetchMoreResults-- | |
| 56 | + | |
| 57 | +```java | |
| 58 | +Statement statement = new SimpleStatement("select * from foo").setFetchSize(20); | |
| 59 | +ListenableFuture<Void> future = Futures.transform( | |
| 60 | + session.executeAsync(statement), | |
| 61 | + iterateFirst()); | |
| 62 | + | |
| 63 | +// Unfortunately we have to special-case for the first page because the signatures of the | |
| 64 | +// futures differ. | |
| 65 | +// In 3.0, fetchMoreResults() will return a Future<ResultSet> to avoid this. | |
| 66 | +private static AsyncFunction<ResultSet, Void> iterateFirst() { | |
| 67 | + return new AsyncFunction<ResultSet, Void>() { | |
| 68 | + @Override | |
| 69 | + public ListenableFuture<Void> apply(ResultSet rs) throws Exception { | |
| 70 | + return iterate(rs, 1).apply(null); | |
| 71 | + } | |
| 72 | + }; | |
| 73 | +} | |
| 74 | + | |
| 75 | +private static AsyncFunction<Void, Void> iterate(final ResultSet rs, final int page) { | |
| 76 | + return new AsyncFunction<Void, Void>() { | |
| 77 | + @Override | |
| 78 | + public ListenableFuture<Void> apply(Void v) throws Exception { | |
| 79 | + | |
| 80 | + // How far we can go without triggering the blocking fetch: | |
| 81 | + int remainingInPage = rs.getAvailableWithoutFetching(); | |
| 82 | + | |
| 83 | + System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage); | |
| 84 | + | |
| 85 | + for (Row row : rs) { | |
| 86 | + System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row); | |
| 87 | + if (--remainingInPage == 0) | |
| 88 | + break; | |
| 89 | + } | |
| 90 | + System.out.printf("Done page %d%n", page); | |
| 91 | + | |
| 92 | + boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null; | |
| 93 | + if (wasLastPage) { | |
| 94 | + System.out.println("Done iterating"); | |
| 95 | + return Futures.immediateFuture(null); | |
| 96 | + } else { | |
| 97 | + ListenableFuture<Void> future = rs.fetchMoreResults(); | |
| 98 | + return Futures.transform(future, iterate(rs, page + 1)); | |
| 99 | + } | |
| 100 | + } | |
| 101 | + }; | |
| 102 | +} | |
| 103 | +``` | |
| 104 | + | |
| 105 | +### Good practices | |
| 106 | + | |
| 107 | +If your callback is slow, consider providing a separate executor. | |
| 108 | +Otherwise the callback might run on one of the driver's I/O threads, | |
| 109 | +blocking I/O operations for other requests while it is running: | |
| 110 | + | |
| 111 | +```java | |
| 112 | +ListenableFuture<String> result = Futures.transform(resultSet, | |
| 113 | + new Function<ResultSet, String>() { | |
| 114 | + public String apply(ResultSet rs) { | |
| 115 | + return someVeryLongComputation(rs); | |
| 116 | + } | |
| 117 | + }, myCustomExecutor); | |
| 118 | +``` | |
| 119 | + | |
| 120 | +Avoid blocking operations in callbacks, especially if you don't provide | |
| 121 | +a separate executor. This could easily lead to deadlock if the thread | |
| 122 | +that's supposed to complete the blocking call is also the thread that's | |
| 123 | +waiting on it: | |
| 124 | + | |
| 125 | +```java | |
| 126 | +ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 127 | + new Function<Session, ResultSet>() { | |
| 128 | + public ResultSet apply(Session session) { | |
| 129 | + // Synchronous operation in a callback. | |
| 130 | + // DON'T DO THIS! It might deadlock. | |
| 131 | + return session.execute("select release_version from system.local"); | |
| 132 | + } | |
| 133 | + }); | |
| 134 | +``` | |
| 135 | + | |
| 136 | +### Known limitations | |
| 137 | + | |
| 138 | +There are still a few places where the driver will block internally | |
| 139 | +(mainly for historical reasons): | |
| 140 | + | |
| 141 | +* [Cluster#init][init] performs blocking I/O operations. To avoid | |
| 142 | + issues, you should create your `Cluster` instances while bootstrapping | |
| 143 | + your application, and call `init` immediately. If you need to create new | |
| 144 | + instances at runtime, make sure this does not happen on an I/O thread. | |
| 145 | +* if a connection pool is busy, the driver will block until a connection | |
| 146 | + becomes available. To avoid this, set | |
| 147 | + [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the | |
| 148 | + driver will not block, just move to the next host immediately. | |
| 149 | +* if the session is set to a specific keyspace (either at startup or by | |
| 150 | + issuing a `USE` statement on a running session), the keyspace needs to | |
| 151 | + be propagated to any newly created connection. This is done when the | |
| 152 | + connection is first borrowed from the connection pool, and currently | |
| 153 | + blocks. To avoid any issue, only use a session with no keyspace set | |
| 154 | + (i.e. created by `Cluster#connect()`). This will be addressed in | |
| 155 | + [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893). | |
| 156 | +* trying to read fields from a [query trace] will block if the trace | |
| 157 | + hasn't been fetched already. | |
| 158 | + | |
| 159 | +[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained | |
| 160 | +[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init() | |
| 161 | +[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 162 | +[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html |
added manual/compression/README.md +88 −0
| @@ -0,0 +1,88 @@ | ||
| 1 | +## Compression | |
| 2 | + | |
| 3 | +Cassandra's binary protocol supports optional compression of | |
| 4 | +transport-level requests and responses, for example: | |
| 5 | + | |
| 6 | +* a query with its serialized parameters; | |
| 7 | +* a [page](../paging/) from a result set, i.e. a list of serialized | |
| 8 | + rows. | |
| 9 | + | |
| 10 | +It reduces network traffic at the cost of CPU overhead, therefore it | |
| 11 | +will likely be beneficial when you have larger payloads. | |
| 12 | + | |
| 13 | +Two algorithms are available: | |
| 14 | +[LZ4](https://github.com/jpountz/lz4-java) and | |
| 15 | +[Snappy](https://code.google.com/p/snappy/). | |
| 16 | +Both rely on third-party libraries, declared by the driver as *optional* | |
| 17 | +dependencies. So If you use a build tool like Maven, you'll need to | |
| 18 | +declare an explicit dependency to pull the appropriate library in your | |
| 19 | +application's classpath. Then you configure compression at driver | |
| 20 | +startup. | |
| 21 | + | |
| 22 | +### LZ4 | |
| 23 | + | |
| 24 | +Maven dependency: | |
| 25 | + | |
| 26 | +```xml | |
| 27 | +<dependency> | |
| 28 | + <groupId>net.jpountz.lz4</groupId> | |
| 29 | + <artifactId>lz4</artifactId> | |
| 30 | + <version>1.2.0</version> | |
| 31 | +</dependency> | |
| 32 | +``` | |
| 33 | + | |
| 34 | +Always check the exact version of the library: go to the driver's | |
| 35 | +[parent POM][pom] (change the URL to match your driver version) and look | |
| 36 | +for the `lz4.version` property. | |
| 37 | + | |
| 38 | +Driver configuration: | |
| 39 | + | |
| 40 | +```java | |
| 41 | +cluster = Cluster.builder() | |
| 42 | + .addContactPoint("127.0.0.1") | |
| 43 | + .withCompression(ProtocolOptions.Compression.LZ4) | |
| 44 | + .build(); | |
| 45 | +``` | |
| 46 | + | |
| 47 | +LZ4-java has three internal implementations (from fastest to slowest): | |
| 48 | + | |
| 49 | +* JNI; | |
| 50 | +* pure Java using sun.misc.Unsafe; | |
| 51 | +* pure Java using only "safe" classes. | |
| 52 | + | |
| 53 | +It will pick the best implementation depending on what's possible on | |
| 54 | +your platform. To find out which one was chosen, [enable INFO | |
| 55 | +logs](../logging/) on the category | |
| 56 | +`com.datastax.driver.core.FrameCompressor` and look for a log similar to | |
| 57 | +this: | |
| 58 | + | |
| 59 | +``` | |
| 60 | +INFO com.datastax.driver.core.FrameCompressor - Using LZ4Factory:JNI | |
| 61 | +``` | |
| 62 | + | |
| 63 | +### Snappy | |
| 64 | + | |
| 65 | +Maven dependency: | |
| 66 | + | |
| 67 | +```xml | |
| 68 | +<dependency> | |
| 69 | + <groupId>org.xerial.snappy</groupId> | |
| 70 | + <artifactId>snappy-java</artifactId> | |
| 71 | + <version>1.0.5</version> | |
| 72 | +</dependency> | |
| 73 | +``` | |
| 74 | + | |
| 75 | +Always check the exact version of the library: go to the driver's | |
| 76 | +[parent POM][pom] (change the URL to match your driver version) and look | |
| 77 | +for the `snappy.version` property. | |
| 78 | + | |
| 79 | +Driver configuration: | |
| 80 | + | |
| 81 | +```java | |
| 82 | +cluster = Cluster.builder() | |
| 83 | + .addContactPoint("127.0.0.1") | |
| 84 | + .withCompression(ProtocolOptions.Compression.SNAPPY) | |
| 85 | + .build(); | |
| 86 | +``` | |
| 87 | + | |
| 88 | +[pom]: https://repo1.maven.org/maven2/com/datastax/cassandra/cassandra-driver-parent/2.1.9/cassandra-driver-parent-2.1.9.pom |
added manual/logging/README.md +303 −0
| @@ -0,0 +1,303 @@ | ||
| 1 | +## Logging | |
| 2 | + | |
| 3 | +### Setup | |
| 4 | + | |
| 5 | +DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages; | |
| 6 | +SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete | |
| 7 | +implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend. | |
| 8 | + | |
| 9 | +The driver itself does not attempt to configure any concrete logging framework. | |
| 10 | +It is up to client applications using the driver to correctly set up their classpath and | |
| 11 | +runtime configuration to be able to capture log messages emitted by the driver. | |
| 12 | +Concretely, client applications need to provide, at runtime, a *binding* to any logging framework | |
| 13 | +of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping). | |
| 14 | + | |
| 15 | +If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file. | |
| 16 | +For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency: | |
| 17 | + | |
| 18 | +```xml | |
| 19 | +<dependency> | |
| 20 | + <groupId>ch.qos.logback</groupId> | |
| 21 | + <artifactId>logback-classic</artifactId> | |
| 22 | + <version>1.1.3</version> | |
| 23 | +</dependency> | |
| 24 | +``` | |
| 25 | + | |
| 26 | +If you are using Log4J 1.2 instead, add the following dependency: | |
| 27 | + | |
| 28 | +```xml | |
| 29 | +<dependency> | |
| 30 | + <groupId>org.slf4j</groupId> | |
| 31 | + <artifactId>slf4j-log4j12</artifactId> | |
| 32 | + <version>1.7.12</version> | |
| 33 | +</dependency> | |
| 34 | +``` | |
| 35 | + | |
| 36 | +Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for | |
| 37 | +other logging frameworks, and for troubleshooting dependency resolution problems. | |
| 38 | + | |
| 39 | +### Configuration | |
| 40 | + | |
| 41 | +Each logging framework has its own configuration rules, but all of them provide | |
| 42 | +different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories* | |
| 43 | +(messages from different categories or loggers can be filtered out separately or printed out | |
| 44 | +differently), and different *appenders* (message receptacles such as the standard console, | |
| 45 | +the error console, a file on disk, a socket...). | |
| 46 | + | |
| 47 | +Check your logging framework documentation for more information about how to properly configure it. | |
| 48 | +You can also find some configuration examples below. | |
| 49 | + | |
| 50 | +### Useful loggers | |
| 51 | + | |
| 52 | +When debugging the Java driver, the following loggers could be particularly useful | |
| 53 | +and provide hints about what's going wrong. | |
| 54 | + | |
| 55 | +* `com.datastax.driver.core.Cluster` | |
| 56 | + * ERROR | |
| 57 | + * Authentication errors | |
| 58 | + * Unexpected errors when handling events, reconnecting, refreshing schemas | |
| 59 | + * Unexpected events | |
| 60 | + * WARN | |
| 61 | + * Cluster name mismatches | |
| 62 | + * Unreachable contact points | |
| 63 | + * Unsupported protocol versions | |
| 64 | + * Schema disagreements | |
| 65 | + * Ignored notifications due to high contention | |
| 66 | + * INFO | |
| 67 | + * Hosts added or removed | |
| 68 | + * DEBUG | |
| 69 | + * Cluster lifecycle (start, shutdown) | |
| 70 | + * Event delivery notifications (schema changes, topology changes) | |
| 71 | + * Topology change events: hosts Up / Down / Added / Removed | |
| 72 | + * Hosts being ignored | |
| 73 | + * Protocol version negotiation | |
| 74 | + * Reconnection attempts | |
| 75 | + * Schema metadata refreshes | |
| 76 | + * TRACE | |
| 77 | + * Connection pools lifecycle (create, renew, refresh) | |
| 78 | +* `com.datastax.driver.core.Session` | |
| 79 | + * ERROR | |
| 80 | + * Errors related to connection pools | |
| 81 | + * WARN | |
| 82 | + * Problems related to connection pools | |
| 83 | + * DEBUG | |
| 84 | + * Connection pools lifecycle (create, renew, refresh) | |
| 85 | +* `com.datastax.driver.core.RequestHandler` | |
| 86 | + * ERROR | |
| 87 | + * Unexpected errors preparing queries | |
| 88 | + * Queries sent to a bootstrapping host | |
| 89 | + * Unexpected server errors | |
| 90 | + * WARN | |
| 91 | + * Queries sent to an overloaded host | |
| 92 | + * INFO | |
| 93 | + * Unprepared queries | |
| 94 | + * DEBUG | |
| 95 | + * Retry attempts | |
| 96 | + * TRACE | |
| 97 | + * Host currently being queried | |
| 98 | +* `com.datastax.driver.core.Connection` | |
| 99 | + * WARN | |
| 100 | + * Problem setting keyspace | |
| 101 | + * Errors closing Netty channel | |
| 102 | + * DEBUG | |
| 103 | + * Connection lifecycle (open, close, defunct) | |
| 104 | + * Error connecting or writing requests | |
| 105 | + * Heartbeats | |
| 106 | + * TRACE | |
| 107 | + * Authentication progress | |
| 108 | + * Sending requests | |
| 109 | + * Receiving responses | |
| 110 | + | |
| 111 | +### Logging query latencies | |
| 112 | + | |
| 113 | +The `QueryLogger` provides clients with the ability to log queries | |
| 114 | +executed by the driver, and especially, it allows client to track slow | |
| 115 | +queries, i.e. queries that take longer to complete than a configured | |
| 116 | +threshold in milliseconds. | |
| 117 | + | |
| 118 | +To turn on this feature, you first need to instantiate and register a `QueryLogger` instance: | |
| 119 | + | |
| 120 | +```java | |
| 121 | +Cluster cluster = ... | |
| 122 | +QueryLogger queryLogger = QueryLogger.builder(cluster) | |
| 123 | + .withConstantThreshold(...) | |
| 124 | + .withMaxQueryStringLength(...) | |
| 125 | +.build(); | |
| 126 | +cluster.register(queryLogger); | |
| 127 | +``` | |
| 128 | + | |
| 129 | +Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide. | |
| 130 | +Besides, you can adjust several parameters such as the maximum query string length to be printed, | |
| 131 | +the maximum number of parameters to print, etc. Refer to the | |
| 132 | +`QueryLogger` [API docs][query_logger] for more information. | |
| 133 | + | |
| 134 | +Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger` | |
| 135 | +uses 3 different loggers: | |
| 136 | + | |
| 137 | +* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds. | |
| 138 | +* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete. | |
| 139 | +* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception. | |
| 140 | + | |
| 141 | +You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries | |
| 142 | +that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above), | |
| 143 | +then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J: | |
| 144 | + | |
| 145 | +```xml | |
| 146 | + <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 147 | + <level value="DEBUG"/> | |
| 148 | + </logger> | |
| 149 | +``` | |
| 150 | + | |
| 151 | +The `QueryLogger` would then print messages such as this for every slow query: | |
| 152 | + | |
| 153 | +``` | |
| 154 | +DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?; | |
| 155 | +``` | |
| 156 | + | |
| 157 | +As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger | |
| 158 | +to TRACE instead, e.g. with Log4J: | |
| 159 | + | |
| 160 | +```xml | |
| 161 | + <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 162 | + <level value="TRACE"/> | |
| 163 | + </logger> | |
| 164 | +``` | |
| 165 | + | |
| 166 | +The `QueryLogger` would then print messages such as this for every slow query: | |
| 167 | + | |
| 168 | +``` | |
| 169 | +TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42]; | |
| 170 | +``` | |
| 171 | + | |
| 172 | +Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters. | |
| 173 | +See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary. | |
| 174 | + | |
| 175 | +#### Constant vs Dynamic thresholds | |
| 176 | + | |
| 177 | +Currently the `QueryLogger` can be configured to track slow queries using either | |
| 178 | +a constant threshold in milliseconds (which is the default behavior), or | |
| 179 | +a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`. | |
| 180 | + | |
| 181 | +**Dynamic thresholds are still a beta feature as of version 2.1.6: they | |
| 182 | +haven't been extensively tested yet, and the API is still subject to | |
| 183 | +change.** | |
| 184 | + | |
| 185 | +Refer to the `QueryLogger` [API docs][query_logger] for an example of usage. | |
| 186 | + | |
| 187 | +### Performance Tips | |
| 188 | + | |
| 189 | +* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html) | |
| 190 | +and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders | |
| 191 | +that can significantly boost latencies when writing log messages. | |
| 192 | +* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration | |
| 193 | +without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html); | |
| 194 | +Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)). | |
| 195 | + | |
| 196 | +### Logback Example | |
| 197 | + | |
| 198 | +Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!* | |
| 199 | + | |
| 200 | +It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file. | |
| 201 | +By default, only messages with ERROR level or higher are logged. | |
| 202 | + | |
| 203 | +It also turns on slow query tracing as described above. | |
| 204 | + | |
| 205 | +```xml | |
| 206 | +<?xml version="1.0" encoding="UTF-8"?> | |
| 207 | +<configuration> | |
| 208 | + | |
| 209 | + <!-- log INFO or higher messages to the console --> | |
| 210 | + <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> | |
| 211 | + <encoder> | |
| 212 | + <pattern>%-5p %msg%n</pattern> | |
| 213 | + </encoder> | |
| 214 | + </appender> | |
| 215 | + | |
| 216 | + <!-- log everything to a rolling file --> | |
| 217 | + <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender"> | |
| 218 | + <file>driver.log</file> | |
| 219 | + <encoder> | |
| 220 | + <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern> | |
| 221 | + </encoder> | |
| 222 | + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> | |
| 223 | + <!-- daily rollover --> | |
| 224 | + <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern> | |
| 225 | + <!-- keep 30 days' worth of history --> | |
| 226 | + <maxHistory>30</maxHistory> | |
| 227 | + </rollingPolicy> | |
| 228 | + </appender> | |
| 229 | + | |
| 230 | + <!-- use AsyncAppender for lower latencies --> | |
| 231 | + <appender name="async" class="ch.qos.logback.classic.AsyncAppender"> | |
| 232 | + <appender-ref ref="console" /> | |
| 233 | + <appender-ref ref="file" /> | |
| 234 | + </appender> | |
| 235 | + | |
| 236 | + <!-- | |
| 237 | + Turn on slow query logging by setting this logger to DEBUG; | |
| 238 | + set level to TRACE to also log query parameters | |
| 239 | + --> | |
| 240 | + <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" /> | |
| 241 | + | |
| 242 | + <root level="ERROR"> | |
| 243 | + <appender-ref ref="async" /> | |
| 244 | + </root> | |
| 245 | + | |
| 246 | +</configuration> | |
| 247 | +``` | |
| 248 | + | |
| 249 | +### Log4J Example | |
| 250 | + | |
| 251 | +Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!* | |
| 252 | + | |
| 253 | +It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file. | |
| 254 | +By default, only messages with ERROR level or higher are logged. | |
| 255 | + | |
| 256 | +It also turns on slow query tracing as described above. | |
| 257 | + | |
| 258 | +```xml | |
| 259 | +<log4j:configuration> | |
| 260 | + | |
| 261 | + <!-- log INFO or higher messages to the console --> | |
| 262 | + <appender name="console" class="org.apache.log4j.ConsoleAppender"> | |
| 263 | + <param name="threshold" value="INFO"/> | |
| 264 | + <layout class="org.apache.log4j.PatternLayout"> | |
| 265 | + <param name="ConversionPattern" value="%-5p %m%n"/> | |
| 266 | + </layout> | |
| 267 | + </appender> | |
| 268 | + | |
| 269 | + <!-- log everything to a rolling file --> | |
| 270 | + <appender name="file" class="org.apache.log4j.RollingFileAppender"> | |
| 271 | + <param name="file" value="driver.log"/> | |
| 272 | + <param name="append" value="false"/> | |
| 273 | + <param name="maxFileSize" value="1GB"/> | |
| 274 | + <param name="maxBackupIndex" value="10"/> | |
| 275 | + <layout class="org.apache.log4j.PatternLayout"> | |
| 276 | + <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/> | |
| 277 | + </layout> | |
| 278 | + </appender> | |
| 279 | + | |
| 280 | + <!-- use AsyncAppender for lower latencies --> | |
| 281 | + <appender name="async" class="org.apache.log4j.AsyncAppender"> | |
| 282 | + <param name="BufferSize" value="500"/> | |
| 283 | + <appender-ref ref="file"/> | |
| 284 | + <appender-ref ref="console"/> | |
| 285 | + </appender> | |
| 286 | + | |
| 287 | + <!-- | |
| 288 | + Turn on slow query logging by setting this logger to DEBUG; | |
| 289 | + set level to TRACE to also log query parameters | |
| 290 | + --> | |
| 291 | + <logger name="com.datastax.driver.core.QueryLogger.SLOW"> | |
| 292 | + <level value="DEBUG"/> | |
| 293 | + </logger> | |
| 294 | + | |
| 295 | + <root> | |
| 296 | + <priority value="ERROR"/> | |
| 297 | + <appender-ref ref="async"/> | |
| 298 | + </root> | |
| 299 | + | |
| 300 | +</log4j:configuration> | |
| 301 | +``` | |
| 302 | + | |
| 303 | +[query_logger]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryLogger.html |
added manual/metadata/README.md +194 −0
| @@ -0,0 +1,194 @@ | ||
| 1 | +## Metadata | |
| 2 | + | |
| 3 | +The driver maintains global information about the Cassandra cluster it | |
| 4 | +is connected to. It is available via | |
| 5 | +[Cluster#getMetadata()][getMetadata]. | |
| 6 | + | |
| 7 | +[getMetadata]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#getMetadata() | |
| 8 | + | |
| 9 | +### Schema metadata | |
| 10 | + | |
| 11 | +Use [getKeyspace(String)][getKeyspace] or [getKeyspaces()][getKeyspaces] | |
| 12 | +to get keyspace-level metadata. From there you can access the keyspace's | |
| 13 | +objects (tables, and UDTs and UDFs if relevant). | |
| 14 | + | |
| 15 | +[getKeyspace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getKeyspace(java.lang.String) | |
| 16 | +[getKeyspaces]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getKeyspaces() | |
| 17 | + | |
| 18 | +#### Refreshes | |
| 19 | + | |
| 20 | +Schema metadata gets refreshed in the following circumstances: | |
| 21 | + | |
| 22 | +* **schema changes via the driver**: after successfully executing a | |
| 23 | + schema-altering query (ex: `CREATE TABLE`), the driver waits for | |
| 24 | + schema agreement (see below), then refreshes the schema. | |
| 25 | +* **third-party schema changes**: if another client (cqlsh, other driver | |
| 26 | + instance...) changes the schema, the driver gets notified by Cassandra | |
| 27 | + via a push notification. It refreshes the schema directly (there is no | |
| 28 | + need to wait for schema agreement since Cassandra has already done it). | |
| 29 | + | |
| 30 | +#### Subscribing to schema changes | |
| 31 | + | |
| 32 | +Users interested in being notified of schema changes can implement the | |
| 33 | +[SchemaChangeListener][SchemaChangeListener] interface. | |
| 34 | + | |
| 35 | +Every listener must [be registered][registerListener] against a `Cluster` instance: | |
| 36 | + | |
| 37 | +```java | |
| 38 | +Cluster cluster = ... | |
| 39 | +SchemaChangeListener myListener = ... | |
| 40 | +cluster.register(myListener); | |
| 41 | +``` | |
| 42 | + | |
| 43 | +Once registered, the listener will be notified of all schema changes detected by the driver, | |
| 44 | +regardless of where they originate from. | |
| 45 | + | |
| 46 | +Note that it is preferable to register a listener only *after* the cluster is fully initialized, | |
| 47 | +otherwise the listener could be notified with a great deal of "Added" events as | |
| 48 | +the driver builds the schema metadata from scratch for the first time. | |
| 49 | + | |
| 50 | +[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SchemaChangeListener.html | |
| 51 | +[registerListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener) | |
| 52 | + | |
| 53 | +#### Schema agreement | |
| 54 | + | |
| 55 | +Schema changes need to be propagated to all nodes in the cluster. Once | |
| 56 | +they have settled on a common version, we say that they are in | |
| 57 | +agreement. | |
| 58 | + | |
| 59 | +As explained above, the driver waits for schema agreement after | |
| 60 | +executing a schema-altering query. This is to ensure that subsequent | |
| 61 | +requests (which might get routed to different nodes) see an up-to-date | |
| 62 | +version of the schema. | |
| 63 | + | |
| 64 | +```ditaa | |
| 65 | + Application Driver Cassandra | |
| 66 | +------+--------------------+------------------+----- | |
| 67 | + | | | | |
| 68 | + | CREATE TABLE... | | | |
| 69 | + |------------------->| | | |
| 70 | + | | send request | | |
| 71 | + | |----------------->| | |
| 72 | + | | | | |
| 73 | + | | success | | |
| 74 | + | |<-----------------| | |
| 75 | + | | | | |
| 76 | + | /--------------------\ | | |
| 77 | + | :Wait until all nodes+------>| | |
| 78 | + | :agree (or timeout) : | | |
| 79 | + | \--------------------/ | | |
| 80 | + | | ^ | | |
| 81 | + | | | | | |
| 82 | + | | +---------| | |
| 83 | + | | | | |
| 84 | + | | refresh schema | | |
| 85 | + | |----------------->| | |
| 86 | + | |<-----------------| | |
| 87 | + | complete query | | | |
| 88 | + |<-------------------| | | |
| 89 | + | | | | |
| 90 | +``` | |
| 91 | + | |
| 92 | +The schema agreement wait is performed synchronously, so the `execute` | |
| 93 | +call -- or the completion of the `ResultSetFuture` if you use the async | |
| 94 | +API -- will only return after it has completed. | |
| 95 | + | |
| 96 | +The check is implemented by repeatedly querying system tables for the | |
| 97 | +schema version reported by each node, until they all converge to the | |
| 98 | +same value. If that doesn't happen within a given timeout, the driver | |
| 99 | +will give up waiting. The default timeout is 10 seconds, it can be | |
| 100 | +customized when building your cluster: | |
| 101 | + | |
| 102 | +```java | |
| 103 | +Cluster cluster = Cluster.builder() | |
| 104 | + .addContactPoint("127.0.0.1") | |
| 105 | + .withMaxSchemaAgreementWaitSeconds(20) | |
| 106 | + .build(); | |
| 107 | +``` | |
| 108 | + | |
| 109 | +After executing a statement, you can check whether schema agreement was | |
| 110 | +successful or timed out: | |
| 111 | + | |
| 112 | +```java | |
| 113 | +ResultSet rs = session.execute("CREATE TABLE..."); | |
| 114 | +if (rs.getExecutionInfo().isSchemaInAgreement()) { | |
| 115 | + // schema is in agreement | |
| 116 | +} else { | |
| 117 | + // schema agreement timed out | |
| 118 | +} | |
| 119 | +``` | |
| 120 | + | |
| 121 | +You can also perform an on-demand check at any time: | |
| 122 | + | |
| 123 | +```java | |
| 124 | +if (cluster.getMetadata().checkSchemaAgreement()) { | |
| 125 | + // schema is in agreement | |
| 126 | +} else { | |
| 127 | + // schema is not in agreement | |
| 128 | +} | |
| 129 | +``` | |
| 130 | + | |
| 131 | +The on-demand check does not retry, it only queries system tables once | |
| 132 | +(so `maxSchemaAgreementWaitSeconds` does not apply). If you need | |
| 133 | +retries, you'll have to schedule them yourself (for example with a | |
| 134 | +custom executor). | |
| 135 | + | |
| 136 | +Check out the API docs for the features in this section: | |
| 137 | + | |
| 138 | +* [withMaxSchemaAgreementWaitSeconds(int)](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.Builder.html#withMaxSchemaAgreementWaitSeconds(int)) | |
| 139 | +* [isSchemaInAgreement()](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ExecutionInfo.html#isSchemaInAgreement()) | |
| 140 | +* [checkSchemaAgreement()](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#checkSchemaAgreement()) | |
| 141 | + | |
| 142 | + | |
| 143 | +### Token metadata | |
| 144 | + | |
| 145 | +This feature is probably of less interest to regular driver users, but | |
| 146 | +it will be useful if you're writing an analytics client on top of the | |
| 147 | +driver. | |
| 148 | + | |
| 149 | +[Metadata][metadata] exposes a number of methods to manipulate tokens | |
| 150 | +and ranges: [getTokenRanges()][getTokenRanges], [getTokenRanges(String | |
| 151 | +keyspace, Host host)][getTokenRanges2], [getReplicas(String keyspace, | |
| 152 | +TokenRange range)][getReplicas], [newToken(String)][newToken] and | |
| 153 | +[newTokenRange(Token start, Token end)][newTokenRange]. | |
| 154 | + | |
| 155 | +[TokenRange][TokenRange] provides various operations on ranges | |
| 156 | +(splitting, merging, etc.). | |
| 157 | + | |
| 158 | +Each host exposes its primary tokens as [getTokens()][getTokens]. | |
| 159 | + | |
| 160 | +Finally, you can inject tokens in CQL queries with | |
| 161 | +[BoundStatement#setToken][setToken], and retrieve them from results with | |
| 162 | +[Row#getToken][getToken] and [Row#getPartitionKeyToken][getPKToken]. | |
| 163 | + | |
| 164 | +As an example, here is how you could compute the splits to partition a | |
| 165 | +job (pseudocode): | |
| 166 | + | |
| 167 | +``` | |
| 168 | +metadata = cluster.getMetadata() | |
| 169 | +for range : metadata.getTokenRanges() { | |
| 170 | + hosts = metadata.getReplicas(keyspace, range) | |
| 171 | + int n = estimateNumberOfSplits() // more on that below | |
| 172 | + for split : range.splitEvenly(n) | |
| 173 | + // pick a host to process split | |
| 174 | +} | |
| 175 | +``` | |
| 176 | + | |
| 177 | +For `estimateNumberOfSplits`, you need a way to estimate the total | |
| 178 | +number of partition keys (this is what analytics clients would | |
| 179 | +traditionally do with the Thrift operation `describe_splits_ex`). | |
| 180 | +Starting with Cassandra 2.1.5, this information is available in a system | |
| 181 | +table (see | |
| 182 | +[CASSANDRA-7688](https://issues.apache.org/jira/browse/CASSANDRA-7688)). | |
| 183 | + | |
| 184 | +[metadata]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html | |
| 185 | +[getTokenRanges]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getTokenRanges() | |
| 186 | +[getTokenRanges2]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getTokenRanges(java.lang.String,%20com.datastax.driver.core.Host) | |
| 187 | +[getReplicas]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#getReplicas(java.lang.String,%20com.datastax.driver.core.TokenRange) | |
| 188 | +[newToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#newToken(java.lang.String) | |
| 189 | +[newTokenRange]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metadata.html#newTokenRange(com.datastax.driver.core.Token,%20com.datastax.driver.core.Token) | |
| 190 | +[TokenRange]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TokenRange.html | |
| 191 | +[getTokens]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Host.html#getTokens() | |
| 192 | +[setToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html#setToken(int,%20com.datastax.driver.core.Token) | |
| 193 | +[getToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Row.html#getToken(int) | |
| 194 | +[getPKToken]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Row.html#getPartitionKeyToken() |
added manual/native_protocol/README.md +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +## Native protocol | |
| 2 | + | |
| 3 | +The native protocol defines the format of the binary messages exchanged | |
| 4 | +between the driver and Cassandra over TCP. As a driver user, you don't | |
| 5 | +need to know the fine details (although the protocol spec is [in the | |
| 6 | +Cassandra codebase][native_spec] if you're curious); the most visible | |
| 7 | +aspect is that some features are only available with specific protocol | |
| 8 | +versions. | |
| 9 | + | |
| 10 | +[native_spec]: https://github.com/apache/cassandra/tree/trunk/doc | |
| 11 | + | |
| 12 | +### Compatibility matrix | |
| 13 | + | |
| 14 | +By default, the protocol version is negotiated between the driver and | |
| 15 | +Cassandra when the first connection is established. Both sides are | |
| 16 | +backward-compatible with older versions: | |
| 17 | + | |
| 18 | +<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 19 | +<tr><td> </td><td>Cassandra: 1.2.x<br/>(DSE 3.2)</td><td>2.0.x<br/>(DSE 4.0 to 4.6)</td><td>2.1.x<br/>(DSE 4.7)</td></tr> | |
| 20 | +<tr><td>Driver: 1.0.x</td> <td>v1</td> <td>v1</td> <td>v1</td> </tr> | |
| 21 | +<tr><td>2.0.x to 2.1.1</td> <td>v1</td> <td>v2</td> <td>v2</td> </tr> | |
| 22 | +<tr><td>2.1.2 or more</td> <td>v1</td> <td>v2</td> <td>v3</td> </tr> | |
| 23 | +</table> | |
| 24 | + | |
| 25 | +For example, if you use version 2.1.5 of the driver to connect to | |
| 26 | +Cassandra 2.0.9, the maximum version you can use (and the one you'll get | |
| 27 | +by default) is protocol v2 (last line, middle column). If you use the | |
| 28 | +same version to connect to Cassandra 2.1.4, you can use protocol v3. | |
| 29 | + | |
| 30 | +### Controlling the protocol version | |
| 31 | + | |
| 32 | +To find out which version you're currently using, use | |
| 33 | +[ProtocolOptions#getProtocolVersionEnum()][gpve]: | |
| 34 | + | |
| 35 | +```java | |
| 36 | +ProtocolVersion myCurrentVersion = cluster.getConfiguration() | |
| 37 | + .getProtocolOptions() | |
| 38 | + .getProtocolVersionEnum(); | |
| 39 | +``` | |
| 40 | + | |
| 41 | +The protocol version can not be changed at runtime. However, you can | |
| 42 | +force a given version at initialization: | |
| 43 | + | |
| 44 | +```java | |
| 45 | +Cluster cluster = Cluster.builder() | |
| 46 | + .addContactPoint("127.0.0.1") | |
| 47 | + .withProtocolVersion(ProtocolVersion.V2) | |
| 48 | + .build(); | |
| 49 | +``` | |
| 50 | + | |
| 51 | +If you specify a version that is not compatible with your current | |
| 52 | +driver/Cassandra combination, you'll get an error: | |
| 53 | + | |
| 54 | +``` | |
| 55 | +Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException: | |
| 56 | +All host(s) tried for query failed | |
| 57 | +(tried: /127.0.0.1:9042 (com.datastax.driver.core.UnsupportedProtocolVersionException: | |
| 58 | + [/127.0.0.1:9042] Host /127.0.0.1:9042 does not support protocol version V3 but V2)) | |
| 59 | +``` | |
| 60 | + | |
| 61 | +[gpve]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersionEnum() | |
| 62 | + | |
| 63 | +#### Protocol version with mixed clusters | |
| 64 | + | |
| 65 | +If you have a cluster with mixed versions (for example, while doing a | |
| 66 | +rolling upgrade of Cassandra), note that **the protocol version will be | |
| 67 | +negotiated with the first host the driver connects to**. | |
| 68 | + | |
| 69 | +This could lead to the following situation (assuming you use driver | |
| 70 | +2.1.2+): | |
| 71 | + | |
| 72 | +* the first contact point is a 2.1 host, so the driver negotiates | |
| 73 | + protocol v3; | |
| 74 | +* while connecting to the rest of the cluster, the driver contacts a 2.0 | |
| 75 | + host using protocol v3, which fails; an error is logged and this host | |
| 76 | + will be permanently ignored. | |
| 77 | + | |
| 78 | +To avoid this issue, you can use one the following workarounds: | |
| 79 | + | |
| 80 | +* always force a protocol version at startup. You keep it at v2 while | |
| 81 | + the rolling upgrade is happening, and only switch to v3 when the whole | |
| 82 | + cluster has switched to Cassandra 2.1; | |
| 83 | +* ensure that the list of initial contact points only contains hosts | |
| 84 | + with the oldest version (2.0 in this example). | |
| 85 | + | |
| 86 | + | |
| 87 | +### New features by protocol version | |
| 88 | + | |
| 89 | +#### v1 to v2 | |
| 90 | + | |
| 91 | +* bound variables in simple statements | |
| 92 | + ([Session#execute(String, Object...)](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#execute(java.lang.String,%20java.lang.Object...))) | |
| 93 | +* [batch statements](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html) | |
| 94 | +* [query paging](../paging/) | |
| 95 | + | |
| 96 | +#### v2 to v3 | |
| 97 | + | |
| 98 | +* the number of stream ids per connection goes from 128 to 32768 (see | |
| 99 | + [Connection pooling](../pooling/)) | |
| 100 | +* [serial consistency on batch statements](http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html#setSerialConsistencyLevel(com.datastax.driver.core.ConsistencyLevel)) | |
| 101 | +* [client-side timestamps](../query_timestamps/) |
added manual/object_mapper/README.md +18 −0
| @@ -0,0 +1,18 @@ | ||
| 1 | +# Object Mapper | |
| 2 | + | |
| 3 | +Version 2.1 of the driver introduces a simple object mapper, which | |
| 4 | +avoids most of the boilerplate when converting your domain classes to | |
| 5 | +and from query results. It handles basic CRUD operations in Cassandra tables | |
| 6 | +containing UDTs, collections and all native CQL types. | |
| 7 | + | |
| 8 | +The mapper is published as a separate Maven artifact: | |
| 9 | + | |
| 10 | +```xml | |
| 11 | +<dependency> | |
| 12 | + <groupId>com.datastax.cassandra</groupId> | |
| 13 | + <artifactId>cassandra-driver-mapping</artifactId> | |
| 14 | + <version>2.1.9</version> | |
| 15 | +</dependency> | |
| 16 | +``` | |
| 17 | + | |
| 18 | +This documentation is organized in subsections describing mapper features. |
added manual/object_mapper/creating/README.md +246 −0
| @@ -0,0 +1,246 @@ | ||
| 1 | +## Definition of mapped classes | |
| 2 | + | |
| 3 | +The object mapper is configured by annotations on the mapped classes. | |
| 4 | + | |
| 5 | +### Creating a table entity | |
| 6 | + | |
| 7 | +A table entity is a class that will be mapped to a table in Cassandra. | |
| 8 | +It is annotated with [@Table][table]: | |
| 9 | + | |
| 10 | +``` | |
| 11 | +CREATE TABLE user (user_id uuid PRIMARY KEY, name text); | |
| 12 | +``` | |
| 13 | + | |
| 14 | +```java | |
| 15 | +@Table(keyspace = "ks", name = "users", | |
| 16 | + readConsistency = "QUORUM", | |
| 17 | + writeConsistency = "QUORUM", | |
| 18 | + caseSensitiveKeyspace = false, | |
| 19 | + caseSensitiveTable = false) | |
| 20 | +public static class User { | |
| 21 | + @PartitionKey | |
| 22 | + @Column(name = "user_id") | |
| 23 | + private UUID userId; | |
| 24 | + private String name; | |
| 25 | + // ... constructors / getters / setters | |
| 26 | +} | |
| 27 | +``` | |
| 28 | + | |
| 29 | +`@Table` takes the following options: | |
| 30 | + | |
| 31 | +- `keyspace`: the keyspace for the table. | |
| 32 | +- `name`: the name of the table in the database. | |
| 33 | +- `caseSensitiveKeyspace`: whether the keyspace name is [case-sensitive]. | |
| 34 | +- `caseSensitiveTable`: whether the table name is [case-sensitive]. | |
| 35 | +- `readConsistency`: the [consistency level] that will be used on each | |
| 36 | + get operation in the mapper. (if unspecified, it defaults to the | |
| 37 | + cluster-wide setting) | |
| 38 | +- `writeConsistency`: the [consistency level] that will be used on each | |
| 39 | + save, or delete operation in the mapper. (if unspecified, it defaults | |
| 40 | + to the cluster-wide setting) | |
| 41 | + | |
| 42 | +The class must provide a default constructor, and all fields (except the | |
| 43 | +ones annotated `@Transient`) must have corresponding setters and | |
| 44 | +getters. | |
| 45 | + | |
| 46 | +[table]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Table.html | |
| 47 | +[case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html | |
| 48 | +[consistency level]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ConsistencyLevel.html | |
| 49 | + | |
| 50 | +#### Column names | |
| 51 | + | |
| 52 | +By default, the mapper tries to map each Java property to a | |
| 53 | +case insensitive column of the same name. If you want to use a different | |
| 54 | +name, or [case-sensitive] names, use the [@Column][column] annotation on | |
| 55 | +the field. | |
| 56 | + | |
| 57 | +[column]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Column.html | |
| 58 | + | |
| 59 | +#### Primary key fields | |
| 60 | + | |
| 61 | +[@PartitionKey][pk] and [@ClusteringColumn][cc] are used to indicate the | |
| 62 | +[partition key][pks] and [clustering columns][pks]. In the case of a | |
| 63 | +composite partition key or multiple clustering columns, the integer | |
| 64 | +value indicates the position of the column in the key: | |
| 65 | + | |
| 66 | +``` | |
| 67 | +CREATE TABLE sales(countryCode text, areaCode text, sales int, | |
| 68 | + PRIMARY KEY((countryCode, area Code))); | |
| 69 | +``` | |
| 70 | + | |
| 71 | +```java | |
| 72 | +@PartitionKey(0) | |
| 73 | +private String countryCode; | |
| 74 | +@PartitionKey(1) | |
| 75 | +private String areaCode; | |
| 76 | +``` | |
| 77 | + | |
| 78 | +The order of the indices must match that of the columns in the table | |
| 79 | +declaration. | |
| 80 | + | |
| 81 | +[pk]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/PartitionKey.html | |
| 82 | +[cc]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/ClusteringColumn.html | |
| 83 | +[pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html | |
| 84 | + | |
| 85 | +#### Enumerations | |
| 86 | + | |
| 87 | +[@Enumerated][enum] is used to map Java enumerations. Since Cassandra | |
| 88 | +does not support enumerations, the object mapper defines two ways to | |
| 89 | +persist an enum value : | |
| 90 | + | |
| 91 | +- `EnumType.ORDINAL` : the value is persisted as a Cassandra's `int` and | |
| 92 | + its value is its position in the enum. | |
| 93 | +- `EnumType.STRING` : the value is persisted as a Cassandra's `text` and | |
| 94 | + its value is its name in the enum. | |
| 95 | + | |
| 96 | +According to the chosen type, the matching database column must be the | |
| 97 | +same type. | |
| 98 | + | |
| 99 | +``` | |
| 100 | +CREATE TABLE person (id uuid PRIMARY KEY, name text, gender int); | |
| 101 | +``` | |
| 102 | + | |
| 103 | +```java | |
| 104 | +@Enumerated(EnumType.ORDINAL) | |
| 105 | +private Gender gender; | |
| 106 | +``` | |
| 107 | + | |
| 108 | +[enum]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Enumerated.html | |
| 109 | + | |
| 110 | +#### Computed fields | |
| 111 | + | |
| 112 | +[@Computed][computed] can be used on fields that are the result of a | |
| 113 | +computation on the Cassandra side. Typically a function call. Native | |
| 114 | +functions in Cassandra like `writetime()` or [User Defined Functions] are | |
| 115 | +supported. | |
| 116 | + | |
| 117 | +```java | |
| 118 | +@Computed("ttl(name)") | |
| 119 | +Integer ttl; | |
| 120 | +``` | |
| 121 | + | |
| 122 | +The CQL return type of function must match the type of the field, | |
| 123 | +otherwise an exception will be thrown. | |
| 124 | + | |
| 125 | +Computed fields are ignored when saving an entity. | |
| 126 | + | |
| 127 | +`@Computed` does not support case-sensitivity. If the expression | |
| 128 | +contains case-sensitive column or function names, you'll have to escape | |
| 129 | +them: | |
| 130 | + | |
| 131 | +```java | |
| 132 | +@Computed("\"myFunction\"(\"myColumn\")") | |
| 133 | +int f; | |
| 134 | +``` | |
| 135 | + | |
| 136 | +Finally, computed fields are only supported with [basic read | |
| 137 | +operations](../using/#basic-crud-operations) at this time. | |
| 138 | +Support in [accessors](../using/#accessors) in planned for a future | |
| 139 | +version (see | |
| 140 | +[JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). | |
| 141 | + | |
| 142 | +[User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ | |
| 143 | +[computed]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Computed.html | |
| 144 | + | |
| 145 | +#### Transient fields | |
| 146 | + | |
| 147 | +[@Transient][transient] can be used to prevent a field from being mapped. | |
| 148 | + | |
| 149 | +[transient]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Transient.html | |
| 150 | + | |
| 151 | +### Mapping User Types | |
| 152 | + | |
| 153 | +[User Defined Types] can also be mapped by using [@UDT][udt]: | |
| 154 | + | |
| 155 | +``` | |
| 156 | +CREATE TYPE address (street text, zip_code int); | |
| 157 | +``` | |
| 158 | + | |
| 159 | +```java | |
| 160 | +@UDT(keyspace = "ks", name = "address") | |
| 161 | +class Address { | |
| 162 | + private String street; | |
| 163 | + @Field(name = "zip_code") | |
| 164 | + private int zipCode; | |
| 165 | + // ... constructors / getters / setters | |
| 166 | +} | |
| 167 | +``` | |
| 168 | + | |
| 169 | +`@UDT` takes the following options: | |
| 170 | + | |
| 171 | +- `keyspace`: the keyspace for the UDT. | |
| 172 | +- `name`: the name of the UDT in the database. | |
| 173 | +- `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. | |
| 174 | +- `caseSensitiveType`: whether the UDT name is case-sensitive. | |
| 175 | + | |
| 176 | +The class must provide a default constructor, and all fields (except the | |
| 177 | +ones annotated `@Transient`) must have corresponding setters and | |
| 178 | +getters. | |
| 179 | + | |
| 180 | +As in table entities, fields are mapped to an UDT field of the same | |
| 181 | +name by default. To declare a different name or use case-sensitivity, | |
| 182 | +use the [@Field][field] annotation: | |
| 183 | + | |
| 184 | +```java | |
| 185 | +@Field(name = "zip_code") | |
| 186 | +private int zipCode; | |
| 187 | +``` | |
| 188 | + | |
| 189 | +When a table has a UDT column, the mapper will automatically map it to | |
| 190 | +the corresponding class: | |
| 191 | + | |
| 192 | +``` | |
| 193 | +CREATE TABLE company (company_id uuid PRIMARY KEY, name text, address address); | |
| 194 | +``` | |
| 195 | + | |
| 196 | +```java | |
| 197 | +public static class Company { | |
| 198 | + @PartitionKey | |
| 199 | + @Column(name = "company_id") | |
| 200 | + private UUID companyId; | |
| 201 | + private String name; | |
| 202 | + private Address address; | |
| 203 | +} | |
| 204 | +``` | |
| 205 | + | |
| 206 | +(this also works with UDTs inside collections or other UDTs, with | |
| 207 | +arbitrary level of nesting) | |
| 208 | + | |
| 209 | +[User Defined Types]:http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/reference/userDefinedTypes.html | |
| 210 | +[udt]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/UDT.html | |
| 211 | +[field]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Field.html | |
| 212 | + | |
| 213 | +### Mapping collections | |
| 214 | + | |
| 215 | +Java collections will be automatically mapped into corresponding | |
| 216 | +Cassandra types. As in Cassandra, collections can contain all native | |
| 217 | +types and all [user types](#mapping-user-types) previously defined is | |
| 218 | +the database. | |
| 219 | + | |
| 220 | +Collection fields must be annotated to indicate whether they are frozen | |
| 221 | +or not (currently this is only for informational purposes, but the | |
| 222 | +mapper will check that the declared state match the rules in Cassandra). | |
| 223 | +The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and | |
| 224 | +[@FrozenValue][frozenvalue]` are also provided for convenience: | |
| 225 | + | |
| 226 | +```java | |
| 227 | +// Will be mapped as a 'list<text>' | |
| 228 | +private List<String> stringList; | |
| 229 | + | |
| 230 | +// Will be mapped as a 'frozen<list<text>>' | |
| 231 | +@Frozen | |
| 232 | +private List<String> frozenStringList; | |
| 233 | + | |
| 234 | +// Will be mapped as 'map<frozen<address>, frozen<list<text>>>' | |
| 235 | +@FrozenKey | |
| 236 | +@FrozenValue | |
| 237 | +private Map<Address, List<String>> frozenKeyValueMap; | |
| 238 | + | |
| 239 | +// Will be mapped as 'map<text, frozen<list<address>>>' | |
| 240 | +@FrozenValue | |
| 241 | +private Map<String, List<Address>> frozenValueMap; | |
| 242 | +``` | |
| 243 | + | |
| 244 | +[frozen]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Frozen.html | |
| 245 | +[frozenkey]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/FrozenKey.html | |
| 246 | +[frozenvalue]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/FrozenValue.html |
added manual/object_mapper/using/README.md +313 −0
| @@ -0,0 +1,313 @@ | ||
| 1 | +## Using the mapper | |
| 2 | + | |
| 3 | +First, create a [MappingManager]. It wraps an existing [Session] | |
| 4 | +instance: | |
| 5 | + | |
| 6 | +```java | |
| 7 | +MappingManager manager = new MappingManager(session); | |
| 8 | +``` | |
| 9 | + | |
| 10 | +`MappingManager` is thread-safe and can be safely shared throughout your | |
| 11 | +application. You would typically create one instance at startup, right | |
| 12 | +after your `Session`. | |
| 13 | + | |
| 14 | +Note that `MappingManager` will initialize the `Session` if not | |
| 15 | +previously done (this was not the case in previous driver versions; if | |
| 16 | +this is a problem for you, see `MappingManager(session, protocolVersion)`). | |
| 17 | + | |
| 18 | +### Entity mappers | |
| 19 | + | |
| 20 | +Each entity class (annotated with `@Table`) is managed by a dedicated | |
| 21 | +[Mapper] object. You obtain this object from the `MappingManager`: | |
| 22 | + | |
| 23 | +```java | |
| 24 | +Mapper<User> mapper = manager.mapper(User.class); | |
| 25 | +``` | |
| 26 | + | |
| 27 | +`Mapper` objects are thread-safe. The manager caches them internally, so | |
| 28 | +calling `manager#mapper` more than once for the same class will return | |
| 29 | +the previously generated mapper. | |
| 30 | + | |
| 31 | +[Mapper]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/Mapper.html | |
| 32 | +[MappingManager]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/MappingManager.html | |
| 33 | +[Session]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html | |
| 34 | + | |
| 35 | +#### Basic CRUD operations | |
| 36 | + | |
| 37 | +To save an object, use `Mapper#save`: | |
| 38 | + | |
| 39 | +```java | |
| 40 | +UUID userId = ...; | |
| 41 | +User u = new User(userId, "John Doe", new Address("street", 01000)); | |
| 42 | +mapper.save(u); | |
| 43 | +``` | |
| 44 | + | |
| 45 | +-------------- | |
| 46 | + | |
| 47 | +To retrieve an object, use `Mapper#get`: | |
| 48 | + | |
| 49 | +```java | |
| 50 | +UUID userId = ...; | |
| 51 | +User u = mapper.get(userId); | |
| 52 | +``` | |
| 53 | + | |
| 54 | +`get`'s arguments must match the partition key components (number of | |
| 55 | +arguments and their types). | |
| 56 | + | |
| 57 | +-------------- | |
| 58 | + | |
| 59 | +To delete a row in a table, use `Mapper#delete`. This method support | |
| 60 | +deleting a row given either its primary keys, or the object to delete: | |
| 61 | + | |
| 62 | +```java | |
| 63 | +UUID userId = ...; | |
| 64 | +mapper.delete(userId); | |
| 65 | +mapper.delete(u); | |
| 66 | +``` | |
| 67 | + | |
| 68 | +-------------- | |
| 69 | + | |
| 70 | +All these CRUD operations are synchronous, but the `Mapper` provides | |
| 71 | +their asynchronous equivalents: | |
| 72 | + | |
| 73 | +```java | |
| 74 | +ListenableFuture<Void> saveFuture = mapper.saveAsync(u); | |
| 75 | +ListenableFuture<User> userFuture = mapper.getAsync(userId); | |
| 76 | +ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId); | |
| 77 | +``` | |
| 78 | + | |
| 79 | +#### Mapper options | |
| 80 | + | |
| 81 | +The basic CRUD operations accept additional options to customize the | |
| 82 | +underlying query: | |
| 83 | + | |
| 84 | +- `ttl`: add a time-to-live value for the operation. | |
| 85 | +- `timestamp`: add a timestamp value for the operation. | |
| 86 | +- `consistencyLevel`: specify a consistency level. | |
| 87 | +- `tracing`: set tracing flag for the query. | |
| 88 | +- `saveNullFields`: if set to true, fields with value `null` in an | |
| 89 | + instance that is to be persisted will be explicitly written as `null` | |
| 90 | + in the query. If set to false, fields with null value won't be included | |
| 91 | + in the write query (thus avoiding tombstones). If not specified, the | |
| 92 | + default behavior is to persist `null` fields. | |
| 93 | + | |
| 94 | +To use options, add them to the mapper call after regular parameters: | |
| 95 | + | |
| 96 | +```java | |
| 97 | +import static com.datastax.driver.mapping.Mapper.Option.*; | |
| 98 | + | |
| 99 | +mapper.save(new User(userId, "helloworld"), | |
| 100 | + timestamp(123456L), tracing(true), ttl(42)); | |
| 101 | +``` | |
| 102 | + | |
| 103 | +Some options don't apply to all operations: | |
| 104 | + | |
| 105 | +<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 106 | + <tr> <td><b>Option</b></td> <td><b>save/saveQuery</b></td> <td><b>get/getQuery</b></td> <td><b>delete/deleteQuery</b></td></tr> | |
| 107 | + <tr> <td>Ttl</td> <td>yes</td> <td>no</td> <td>no</td> </tr> | |
| 108 | + <tr> <td>Timestamp</td> <td>yes</td> <td>no</td> <td>yes</td> </tr> | |
| 109 | + <tr> <td>ConsistencyLevel</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> | |
| 110 | + <tr> <td>Tracing</td> <td>yes</td> <td>yes</td> <td>yes</td> </tr> | |
| 111 | + <tr> <td>SaveNullFields</td> <td>yes</td> <td>no</td> <td>no</td> </tr> | |
| 112 | +</table> | |
| 113 | + | |
| 114 | +Note that `Option.consistencyLevel` is redundant with the consistency | |
| 115 | +level defined by [@Table](../creating/#creating-a-table-entity). | |
| 116 | +If both are defined, the option will take precedence over the | |
| 117 | +annotation. | |
| 118 | + | |
| 119 | +Default options can be defined for each type of operation: | |
| 120 | + | |
| 121 | +```java | |
| 122 | +mapper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM)); | |
| 123 | +mapper.setDefaultSaveOption(saveNullFields(false)); | |
| 124 | +mapper.setDefaultDeleteOption(consistencyLevel(ONE)); | |
| 125 | + | |
| 126 | +// Given the defaults above, this will use tracing(true), consistencyLevel(ONE) | |
| 127 | +mapper.get(uuid, consistencyLevel(ONE)); | |
| 128 | +``` | |
| 129 | + | |
| 130 | +To reset default options, use the following methods: | |
| 131 | + | |
| 132 | +```java | |
| 133 | +mapper.resetDefaultGetOption(); | |
| 134 | +mapper.resetDefaultSaveOption(); | |
| 135 | +mapper.resetDefaultDeleteOption(); | |
| 136 | +``` | |
| 137 | + | |
| 138 | +#### Access to underlying `Statement`s | |
| 139 | + | |
| 140 | +Instead of performing an operation directly, it's possible to ask the | |
| 141 | +`Mapper` to just return the corresponding `Statement` object. This gives | |
| 142 | +the client a chance to customize the statement before executing it. | |
| 143 | + | |
| 144 | +- `Mapper.saveQuery(entity)`: returns a statement generated by the | |
| 145 | + mapper to save `entity` into the database. | |
| 146 | +- `Mapper.getQuery(userId)`: returns a statement to select a row in the | |
| 147 | + database, selected on the given `userId`, and matching the mapped | |
| 148 | + object structure. | |
| 149 | +- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the | |
| 150 | + database given the `userId` provided. This method can also accept a | |
| 151 | + mapped object instance. | |
| 152 | + | |
| 153 | +#### Manual mapping | |
| 154 | + | |
| 155 | +`Mapper#map` provides a way to converts the results of a regular query: | |
| 156 | + | |
| 157 | +```java | |
| 158 | +ResultSet results = session.execute("SELECT * FROM user"); | |
| 159 | +Result<User> users = mapper.map(results); | |
| 160 | +for (User u : users) { | |
| 161 | + System.out.println("User : " + u.getUserId()); | |
| 162 | +} | |
| 163 | +``` | |
| 164 | + | |
| 165 | +This method will ignore: | |
| 166 | + | |
| 167 | +* extra columns in the `ResultSet` that are not mapped for this entity. | |
| 168 | +* mapped fields that are not present in the `ResultSet` (setters won't | |
| 169 | + be called so the value will be the one after invocation of the class's | |
| 170 | + default constructor). | |
| 171 | + | |
| 172 | +[Result] is similar to `ResultSet` but for a given mapped class. | |
| 173 | +It provides methods `one()`, `all()`, `iterator()`, `getExecutionInfo()` | |
| 174 | +and `isExhausted()`. Note that iterating the `Result` will consume the | |
| 175 | +`ResultSet`, and vice-versa. | |
| 176 | + | |
| 177 | +[Result]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/Result.html | |
| 178 | + | |
| 179 | +### UDT Mappers | |
| 180 | + | |
| 181 | +A UDT will be automatically mapped when it is part of a table-level | |
| 182 | +class (as shown [here](../creating/#mapping-user-types)). | |
| 183 | + | |
| 184 | +However, there might be cases where it is useful to convert a mapped | |
| 185 | +instance to the corresponding [UDTValue][UDTValue] (and back). The | |
| 186 | +mapper provides an [UDTMapper] for that purpose: | |
| 187 | + | |
| 188 | +```java | |
| 189 | +UDTMapper<Address> addressMapper = manager.getUDTMapper(Address.class); | |
| 190 | +Address address = addressMapper.fromUDT(udtValue); | |
| 191 | +UDTValue value = addressMapper.toUDT(address); | |
| 192 | +``` | |
| 193 | + | |
| 194 | +[UDTValue]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/UDTValue.html | |
| 195 | +[UDTMapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/UDTMapper.html | |
| 196 | + | |
| 197 | +### Accessors | |
| 198 | + | |
| 199 | +`Accessor`s provide a way to map custom queries not supported by the | |
| 200 | +default entity mappers. | |
| 201 | + | |
| 202 | +To create an accessor, define a Java interface and annotate each method | |
| 203 | +to provide the corresponding CQL query: | |
| 204 | + | |
| 205 | +```java | |
| 206 | +@Accessor | |
| 207 | +public interface UserAccessor { | |
| 208 | + @Query("SELECT * FROM user") | |
| 209 | + Result<User> getAll(); | |
| 210 | +} | |
| 211 | +``` | |
| 212 | + | |
| 213 | +The `MappingManager` can then process this class and generate an | |
| 214 | +implementation: | |
| 215 | + | |
| 216 | +```java | |
| 217 | +UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); | |
| 218 | +User user = userAccessor.getOne(uuid); | |
| 219 | +``` | |
| 220 | + | |
| 221 | +Like mappers, accessors are cached at the manager level and thus, are | |
| 222 | +thread-safe/sharable. | |
| 223 | + | |
| 224 | +#### Parameters | |
| 225 | + | |
| 226 | +A query can have bind markers, that will be set with the method's | |
| 227 | +arguments. | |
| 228 | + | |
| 229 | +With unnamed markers, the order of the arguments must match the order of | |
| 230 | +the markers: | |
| 231 | + | |
| 232 | +```java | |
| 233 | +@Query("insert into user (id, name) values (?, ?)") | |
| 234 | +ResultSet insert(UUID userId, String name); | |
| 235 | +``` | |
| 236 | + | |
| 237 | +With named markers, use [@Param][param] to indicate which parameter | |
| 238 | +corresponds to which marker: | |
| 239 | + | |
| 240 | +```java | |
| 241 | +@Query("insert into user (userId, name) values (:u, :n)") | |
| 242 | +ResultSet insert(@Param("u") UUID userId, @Param("n") String name); | |
| 243 | +``` | |
| 244 | + | |
| 245 | +[param]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/Param.html | |
| 246 | + | |
| 247 | +If a method argument is a Java enumeration, it must be annotated with | |
| 248 | +`@Enumerated` to indicate how to convert it to a CQL type (the rules are | |
| 249 | +the same as in [mapping definition](../creating/#enumerations)): | |
| 250 | + | |
| 251 | +```java | |
| 252 | +@Query("insert into user (key, gender) values (?,?)") | |
| 253 | +ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value); | |
| 254 | +``` | |
| 255 | + | |
| 256 | +#### Return type | |
| 257 | + | |
| 258 | +The declared return type of each method affects how the query will get | |
| 259 | +executed: | |
| 260 | + | |
| 261 | +<table border="1" style="text-align:center; width:100%;margin-bottom:1em;"> | |
| 262 | + <tr> <td><b>Return type</b></td> <td><b>Effect</b></td> </tr> | |
| 263 | + <tr> | |
| 264 | + <td><code>void</code></td> | |
| 265 | + <td>Synchronous execution, discards the results of the query.</td> | |
| 266 | + </tr> | |
| 267 | + <tr> | |
| 268 | + <td><code>ResultSet</code></td> | |
| 269 | + <td>Synchronous execution, returns unmapped results.</td> | |
| 270 | + </tr> | |
| 271 | + <tr> | |
| 272 | + <td><code>T</code></td> | |
| 273 | + <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns the first row (or <code>null</code> if there are no results).</td> | |
| 274 | + </tr> | |
| 275 | + <tr> | |
| 276 | + <td><code>Result<T></code></td> | |
| 277 | + <td><code>T</code> must be a mapped class.<br/>Synchronous execution, returns a list of mapped objects.</td> | |
| 278 | + </tr> | |
| 279 | + <tr> | |
| 280 | + <td><code>ResultSetFuture</code></td> | |
| 281 | + <td>Asynchronous execution, returns unmapped results.</td> | |
| 282 | + </tr> | |
| 283 | + <tr> | |
| 284 | + <td><code>ListenableFuture<T></code></td> | |
| 285 | + <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns the first row (or <code>null</code> if there are no results).</td> | |
| 286 | + </tr> | |
| 287 | + <tr> | |
| 288 | + <td><code>ListenableFuture<Result<T>></code></td> | |
| 289 | + <td><code>T</code> must be a mapped class.<br/>Asynchronous execution, returns a list of mapped objects.</td> | |
| 290 | + </tr> | |
| 291 | +</table> | |
| 292 | + | |
| 293 | +Example: | |
| 294 | + | |
| 295 | +```java | |
| 296 | +@Query("SELECT * FROM user") | |
| 297 | +public ListenableFuture<Result<User>> getAllAsync(); | |
| 298 | +``` | |
| 299 | + | |
| 300 | + | |
| 301 | +#### Customizing the statement | |
| 302 | + | |
| 303 | +It is possible to customize query parameters to include in a `Accessor` | |
| 304 | +query with the annotation [@QueryParameters]. Then, options like | |
| 305 | +*consistency level*, *fetchsize* or *tracing* are settable: | |
| 306 | + | |
| 307 | +```java | |
| 308 | +@Query("SELECT * FROM ks.users") | |
| 309 | +@QueryParameters(consistency="QUORUM") | |
| 310 | +public ListenableFuture<Result<User>> getAllAsync(); | |
| 311 | +``` | |
| 312 | + | |
| 313 | +[@QueryParameters]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/mapping/annotations/QueryParameters.html |
added manual/paging/README.md +269 −0
| @@ -0,0 +1,269 @@ | ||
| 1 | +## Paging | |
| 2 | + | |
| 3 | +When a query returns many rows, it would be inefficient to return them | |
| 4 | +as a single response message. Instead, the driver breaks the results | |
| 5 | +into *pages* which get returned as they are needed. | |
| 6 | + | |
| 7 | +### Setting the fetch size | |
| 8 | + | |
| 9 | +The *fetch size* specifies how many rows will be returned at once by | |
| 10 | +Cassandra (in other words, it's the size of each page). | |
| 11 | + | |
| 12 | +You can set a default fetch size globally for a `Cluster` instance: | |
| 13 | + | |
| 14 | +```java | |
| 15 | +// At initialization: | |
| 16 | +Cluster cluster = Cluster.builder() | |
| 17 | + .addContactPoint("127.0.0.1") | |
| 18 | + .withQueryOptions(new QueryOptions().setFetchSize(2000)) | |
| 19 | + .build(); | |
| 20 | + | |
| 21 | +// Or at runtime: | |
| 22 | +cluster.getConfiguration().getQueryOptions().setFetchSize(2000); | |
| 23 | +``` | |
| 24 | + | |
| 25 | +The fetch size can also be set on a statement: | |
| 26 | + | |
| 27 | +```java | |
| 28 | +Statement statement = new SimpleStatement("your query"); | |
| 29 | +statement.setFetchSize(2000); | |
| 30 | +``` | |
| 31 | + | |
| 32 | +If the fetch size is set on a statement, it will take precedence; | |
| 33 | +otherwise, the cluster-wide value (which defaults to 5000) will be used. | |
| 34 | + | |
| 35 | +Note that setting a fetch size doesn't mean that Cassandra will always | |
| 36 | +return the exact number of rows, it is possible that it returns slightly | |
| 37 | +more or less results. | |
| 38 | + | |
| 39 | +### Result set iteration | |
| 40 | + | |
| 41 | +The fetch size limits the number of results that are returned in one | |
| 42 | +page; if you iterate past that, the driver will run background queries | |
| 43 | +to fetch subsequent pages. Here's an example with a fetch size of 20: | |
| 44 | + | |
| 45 | +```ditaa | |
| 46 | + client Session Cassandra | |
| 47 | + --+--------------+---------------------------------+----- | |
| 48 | + |execute(query)| | | |
| 49 | + |------------->| | | |
| 50 | + | | query rows 1 to 20 | | |
| 51 | + | |-------------------------------->| | |
| 52 | + | | | | |
| 53 | + | |create | | |
| 54 | + | |------>ResultSet | | |
| 55 | + | | | | |
| 56 | ++-----+--------+-----------------+-+ | | |
| 57 | +|For i in 1..20| | | | | |
| 58 | ++--------------+ | | | | |
| 59 | +| | get next row | | | | |
| 60 | +| |------------------------->| | | | |
| 61 | +| | row i | | | | |
| 62 | +| |<-------------------------| | | | |
| 63 | +| | | | | | |
| 64 | ++-----+--------------------------+-+ | | |
| 65 | + | | | | |
| 66 | + | | | | |
| 67 | + | get next row | | | |
| 68 | + |------------------------->| | | |
| 69 | + | | query rows 21 to 40 | | |
| 70 | + | |-------------------->| | |
| 71 | + | row 21 | | | |
| 72 | + |<------------------------ | | | |
| 73 | +``` | |
| 74 | + | |
| 75 | +By default, the background fetch happens at the last moment, when there | |
| 76 | +are no more "local" rows available. If you need finer control, the | |
| 77 | +[ResultSet][result_set] interface provides the following methods: | |
| 78 | + | |
| 79 | +* `getAvailableWithoutFetching()` and `isFullyFetched()` to check the | |
| 80 | + current state; | |
| 81 | +* `fetchMoreResults()` to force a page fetch. | |
| 82 | + | |
| 83 | +Here's how you could use these methods to pre-fetch the next page in | |
| 84 | +advance, in order to avoid the performance hit at the end of each page: | |
| 85 | + | |
| 86 | +```java | |
| 87 | +ResultSet rs = session.execute("your query"); | |
| 88 | +for (Row row : rs) { | |
| 89 | + if (rs.getAvailableWithoutFetching() == 100 && !rs.isFullyFetched()) | |
| 90 | + rs.fetchMoreResults(); // this is asynchronous | |
| 91 | + // Process the row ... | |
| 92 | + System.out.println(row); | |
| 93 | +} | |
| 94 | +``` | |
| 95 | + | |
| 96 | +If you use paging with the async API, you'll also want to use those | |
| 97 | +methods to avoid triggering synchronous fetches unintentionally; see | |
| 98 | +[async paging](../async/#async-paging). | |
| 99 | + | |
| 100 | + | |
| 101 | +### Saving and reusing the paging state | |
| 102 | + | |
| 103 | +Sometimes it is convenient to save the paging state in order to restore | |
| 104 | +it later. For example, consider a stateless web service that displays a | |
| 105 | +list of results with a link to the next page. When the user clicks that | |
| 106 | +link, we want to run the exact same query, except that the iteration | |
| 107 | +should start where we stopped on the previous page. | |
| 108 | + | |
| 109 | +To do so, the driver exposes a [PagingState][paging_state] object that represents | |
| 110 | +where we were in the result set when the last page was fetched: | |
| 111 | + | |
| 112 | +```java | |
| 113 | +ResultSet resultSet = session.execute("your query"); | |
| 114 | +// iterate the result set... | |
| 115 | +PagingState pagingState = resultSet.getExecutionInfo().getPagingState(); | |
| 116 | +``` | |
| 117 | + | |
| 118 | +This object can be serialized to a `String` or a byte array: | |
| 119 | + | |
| 120 | +```java | |
| 121 | +String string = pagingState.toString(); | |
| 122 | +byte[] bytes = pagingState.toBytes(); | |
| 123 | +``` | |
| 124 | + | |
| 125 | +This serialized form can be saved in some form of persistent storage to | |
| 126 | +be reused later. In our web service example, we would probably save the | |
| 127 | +string version as a query parameter in the URL to the next page | |
| 128 | +(`http://myservice.com/results?page=<...>`). When that value is | |
| 129 | +retrieved later, we can deserialize it and reinject it in a statement: | |
| 130 | + | |
| 131 | +```java | |
| 132 | +PagingState pagingState = PagingState.fromString(string); | |
| 133 | +Statement st = new SimpleStatement("your query"); | |
| 134 | +st.setPagingState(pagingState); | |
| 135 | +ResultSet rs = session.execute(st); | |
| 136 | +``` | |
| 137 | + | |
| 138 | +Note that the paging state can only be reused with the exact same | |
| 139 | +statement (same query string, same parameters). Also, it is an opaque | |
| 140 | +value that is only meant to be collected, stored an re-used. If you try | |
| 141 | +to modify its contents or reuse it with a different statement, the | |
| 142 | +driver will raise an error. | |
| 143 | + | |
| 144 | +Putting it all together, here's a more comprehensive example | |
| 145 | +implementation for our web service: | |
| 146 | + | |
| 147 | +```java | |
| 148 | +final int RESULTS_PER_PAGE = 100; | |
| 149 | + | |
| 150 | +Statement st = new SimpleStatement("your query"); | |
| 151 | +st.setFetchSize(RESULTS_PER_PAGE); | |
| 152 | + | |
| 153 | +String requestedPage = extractPagingStateStringFromURL(); | |
| 154 | +// This will be absent for the first page | |
| 155 | +if (requestedPage != null) { | |
| 156 | + st.setPagingState( | |
| 157 | + PagingState.fromString(requestedPage)); | |
| 158 | +} | |
| 159 | + | |
| 160 | +ResultSet rs = session.execute(st); | |
| 161 | +PagingState nextPage = rs.getExecutionInfo().getPagingState(); | |
| 162 | + | |
| 163 | +// Note that we don't rely on RESULTS_PER_PAGE, since Cassandra might | |
| 164 | +// have not respected it, or we might be at the end of the result set | |
| 165 | +int remaining = rs.getAvailableWithoutFetching(); | |
| 166 | +for (Row row : rs) { | |
| 167 | + renderInResponse(row); | |
| 168 | + if (--remaining == 0) { | |
| 169 | + break; | |
| 170 | + } | |
| 171 | +} | |
| 172 | + | |
| 173 | +// This will be null if there are no more pages | |
| 174 | +if (nextPage != null) { | |
| 175 | + renderNextPageLink(nextPage.toString()); | |
| 176 | +} | |
| 177 | +``` | |
| 178 | + | |
| 179 | +[result_set]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html | |
| 180 | +[paging_state]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PagingState.html | |
| 181 | + | |
| 182 | + | |
| 183 | +Due to internal implementation details, `PagingState` instances are not | |
| 184 | +portable across [native protocol](../native_protocol/) versions. This | |
| 185 | +could become a problem in the following scenario: | |
| 186 | + | |
| 187 | +* you're using the driver 2.0.x and Cassandra 2.0.x, and therefore | |
| 188 | + native protocol v2; | |
| 189 | +* a user bookmarks a link to your web service that contains a serialized | |
| 190 | + paging state; | |
| 191 | +* you upgrade your server stack to use the driver 2.1.x and Cassandra | |
| 192 | + 2.1.x, so you're now using protocol v3; | |
| 193 | +* the user tries to reload their bookmark, but the paging state was | |
| 194 | + serialized with protocol v2, so trying to reuse it will fail. | |
| 195 | + | |
| 196 | +If this is not acceptable for you, you might want to consider the unsafe | |
| 197 | +API described in the next section. | |
| 198 | + | |
| 199 | +#### Unsafe API | |
| 200 | + | |
| 201 | +As an alternative to the standard API, there are two methods that | |
| 202 | +manipulate a raw `byte[]` instead of a `PagingState` object: | |
| 203 | + | |
| 204 | +* [ExecutionInfo#getPagingStateUnsafe()][gpsu] | |
| 205 | +* [Statement#setPagingStateUnsafe(byte[])][spsu] | |
| 206 | + | |
| 207 | +These low-level methods perform no validation on their arguments; | |
| 208 | +therefore nothing protects you from reusing a paging state that was | |
| 209 | +generated from a different statement, or altered in any way. This could | |
| 210 | +result in sending a corrupt paging state to Cassandra, with | |
| 211 | +unpredictable consequences (ranging from wrong results to a query | |
| 212 | +failure). | |
| 213 | + | |
| 214 | +There are two situations where you might want to use the unsafe API: | |
| 215 | + | |
| 216 | +* you never expose the paging state to end users and you are confident | |
| 217 | + that it won't get altered; | |
| 218 | +* you want portability across protocol versions and/or you prefer | |
| 219 | + implementing your own validation logic (for example, signing the raw | |
| 220 | + state with a private key). | |
| 221 | + | |
| 222 | +[gpsu]: http://www.datastax.com/drivers/java/2.1/com/datastax/driver/core/ExecutionInfo.html#getPagingStateUnsafe() | |
| 223 | +[spsu]: http://www.datastax.com/drivers/java/2.1/com/datastax/driver/core/Statement.html#setPagingStateUnsafe(byte[]) | |
| 224 | + | |
| 225 | + | |
| 226 | +### Offset queries | |
| 227 | + | |
| 228 | +Saving the paging state works well when you only let the user move from | |
| 229 | +one page to the next. But it doesn't allow random jumps (like "go | |
| 230 | +directly to page 10"), because you can't fetch a page unless you have | |
| 231 | +the paging state of the previous one. Such a feature would require | |
| 232 | +*offset queries*, but they are not natively supported by Cassandra (see | |
| 233 | +[CASSANDRA-6511](https://issues.apache.org/jira/browse/CASSANDRA-6511)). | |
| 234 | +The rationale is that offset queries are inherently inefficient (the | |
| 235 | +performance will always be linear in the number of rows skipped), so the | |
| 236 | +Cassandra team doesn't want to encourage their use. | |
| 237 | + | |
| 238 | +If you really want offset queries, you can emulate them client-side. | |
| 239 | +You'll still get linear performance, but maybe that's acceptable for | |
| 240 | +your use case. For example, if each page holds 10 rows and you show at | |
| 241 | +most 20 pages, this means you'll fetch at most 190 extra rows, which | |
| 242 | +doesn't sound like a big deal. | |
| 243 | + | |
| 244 | +For example, if the page size is 10, the fetch size is 50, and the user | |
| 245 | +asks for page 12 (rows 110 to 119): | |
| 246 | + | |
| 247 | +* execute the statement a first time (the result set contains rows 0 to | |
| 248 | + 49, but you're not going to use them, only the paging state); | |
| 249 | +* execute the statement a second time with the paging state from the | |
| 250 | + first query; | |
| 251 | +* execute the statement a third time with the paging state from the | |
| 252 | + second query. The result set now contains rows 100 to 149; | |
| 253 | +* skip the first 10 rows of the iterator. Read the next 10 rows and | |
| 254 | + discard the remaining ones. | |
| 255 | + | |
| 256 | +You'll want to experiment with the fetch size to find the best balance: | |
| 257 | +too small means many background queries; too big means bigger messages | |
| 258 | +and too many unneeded rows returned (we picked 50 above for the sake of | |
| 259 | +example, but it's probably too small -- the default is 5000). | |
| 260 | + | |
| 261 | +Again, offset queries are inefficient by nature. Emulating them | |
| 262 | +client-side is a compromise when you think you can get away with the | |
| 263 | +performance hit. We recommend that you: | |
| 264 | + | |
| 265 | +* test your code at scale with the expected query patterns, to make sure | |
| 266 | + that your assumptions are correct; | |
| 267 | +* set a hard limit on the highest possible page number, to prevent | |
| 268 | + malicious users from triggering queries that would skip a huge amount | |
| 269 | + of rows. |
added manual/pooling/README.md +290 −0
| @@ -0,0 +1,290 @@ | ||
| 1 | +## Connection pooling | |
| 2 | + | |
| 3 | +### Basics | |
| 4 | + | |
| 5 | +The driver communicates with Cassandra over TCP, using the Cassandra | |
| 6 | +binary protocol. This protocol is asynchronous, which allows each TCP | |
| 7 | +connection to handle multiple simultaneous requests: | |
| 8 | + | |
| 9 | +* when a query gets executed, a *stream id* gets assigned to it. It is a | |
| 10 | + unique identifier on the current connection; | |
| 11 | +* the driver writes a request containing the stream id and the query on | |
| 12 | + the connection, and then proceeds without waiting for the response (if | |
| 13 | + you're using the asynchronous API, this is when the driver will send you | |
| 14 | + back a [ResultSetFuture][result_set_future]). | |
| 15 | + Once the request has been written to the | |
| 16 | + connection, we say that it is *in flight*; | |
| 17 | +* at some point, Cassandra will send back a response on the connection. | |
| 18 | + This response also contains the stream id, which allows the driver to | |
| 19 | + trigger a callback that will complete the corresponding query (this is | |
| 20 | + the point where your `ResultSetFuture` will get completed). | |
| 21 | + | |
| 22 | +To increase the number of concurrent requests, we use a pool of | |
| 23 | +connections to each host. **For each `Session` object, there is one | |
| 24 | +connection pool per connected host**. | |
| 25 | + | |
| 26 | +The number of connections per pool is configurable (this will be | |
| 27 | +described in the next section). The number of stream ids depends on the | |
| 28 | +[native protocol version](../native_protocol/): | |
| 29 | + | |
| 30 | +* protocol v2 or below: 128 stream ids per connection. | |
| 31 | +* protocol v3 or above: up to 32768 stream ids per connection. | |
| 32 | + | |
| 33 | +```ditaa | |
| 34 | ++-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+ | |
| 35 | +|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+ | |
| 36 | ++-------+ +-------+ +----+ +----------+ +-------+ | |
| 37 | +``` | |
| 38 | + | |
| 39 | +### Configuring the connection pool | |
| 40 | + | |
| 41 | +Connections pools are configured with a [PoolingOptions][pooling_options] object, which | |
| 42 | +is global to a `Cluster` instance. You can pass that object when | |
| 43 | +building the cluster: | |
| 44 | + | |
| 45 | +```java | |
| 46 | +PoolingOptions poolingOptions = new PoolingOptions(); | |
| 47 | +// customize options... | |
| 48 | + | |
| 49 | +Cluster cluster = Cluster.builder() | |
| 50 | + .withContactPoints("127.0.0.1") | |
| 51 | + .withPoolingOptions(poolingOptions) | |
| 52 | + .build(); | |
| 53 | +``` | |
| 54 | + | |
| 55 | +Most options can also be changed at runtime. If you don't have a | |
| 56 | +reference to the `PoolingOptions` instance, here's how you can get it: | |
| 57 | + | |
| 58 | +```java | |
| 59 | +PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); | |
| 60 | +// customize options... | |
| 61 | +``` | |
| 62 | + | |
| 63 | +#### Pool size | |
| 64 | + | |
| 65 | +Connection pools have a variable size, which gets adjusted automatically | |
| 66 | +depending on the current load. There will always be at least a *core* | |
| 67 | +number of connections, and at most a *max* number. These values can be | |
| 68 | +configured independently by host *distance* (the distance is determined | |
| 69 | +by your [LoadBalancingPolicy][lbp], and will generally indicate whether a | |
| 70 | +host is in the same datacenter or not). | |
| 71 | + | |
| 72 | +```java | |
| 73 | +poolingOptions | |
| 74 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, 4) | |
| 75 | + .setMaxConnectionsPerHost( HostDistance.LOCAL, 10) | |
| 76 | + .setCoreConnectionsPerHost(HostDistance.REMOTE, 2) | |
| 77 | + .setMaxConnectionsPerHost( HostDistance.REMOTE, 4); | |
| 78 | +``` | |
| 79 | + | |
| 80 | +For convenience, core and max can be set simultaneously: | |
| 81 | + | |
| 82 | +```java | |
| 83 | +poolingOptions | |
| 84 | + .setConnectionsPerHost(HostDistance.LOCAL, 4, 10) | |
| 85 | + .setConnectionsPerHost(HostDistance.REMOTE, 2, 4); | |
| 86 | +``` | |
| 87 | + | |
| 88 | +The default settings are: | |
| 89 | + | |
| 90 | +* protocol v2: | |
| 91 | + * `LOCAL` hosts: core = 2, max = 8 | |
| 92 | + * `REMOTE` hosts: core = 1, max = 2 | |
| 93 | +* protocol v3: | |
| 94 | + * `LOCAL` hosts: core = max = 1 | |
| 95 | + * `REMOTE` hosts: core = max = 1 | |
| 96 | + | |
| 97 | +[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold | |
| 98 | +that triggers the creation of a new connection when the pool is not at | |
| 99 | +its maximum capacity. In general, you shouldn't need to change its | |
| 100 | +default value. | |
| 101 | + | |
| 102 | +#### Dynamic resizing | |
| 103 | + | |
| 104 | +If core != max, the pool will resize automatically to adjust to the | |
| 105 | +current activity on the host. | |
| 106 | + | |
| 107 | +When activity goes up and there are *n* connections with n < max, the driver | |
| 108 | +will add a connection when the number of concurrent requests is more than | |
| 109 | +(n - 1) * 128 + [PoolingOptions.setNewConnectionThreshold][nct] | |
| 110 | +(in layman's terms, when all but the last connection are full and the last | |
| 111 | +connection is above the threshold). | |
| 112 | + | |
| 113 | +When activity goes down, the driver will "trash" connections if the maximum | |
| 114 | +number of requests in a 10 second time period can be satisfied by less than | |
| 115 | +the number of connections opened. Trashed connections are kept open but do | |
| 116 | +not accept new requests. After a given timeout (defined by | |
| 117 | +[PoolingOptions.setIdleTimeoutSeconds][sits]), trashed connections are closed | |
| 118 | +and removed. If during that idle period activity increases again, those | |
| 119 | +connections will be resurrected back into the active pool and reused. The | |
| 120 | +main intent of that is to not constantly recreate connections if activity | |
| 121 | +changes quickly over an interval. | |
| 122 | + | |
| 123 | +#### Simultaneous requests per connection | |
| 124 | + | |
| 125 | +[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to | |
| 126 | +throttle the number of concurrent requests per connection. | |
| 127 | + | |
| 128 | +With protocol v2, there is no reason to throttle. It is set to 128 (the | |
| 129 | +max) and you should not change it. | |
| 130 | + | |
| 131 | +With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for | |
| 132 | +`REMOTE` hosts. These low defaults were chosen so that the default | |
| 133 | +configuration for protocol v2 and v3 allow the same total number of | |
| 134 | +simultaneous requests (to avoid bad surprises when clients migrate from | |
| 135 | +v2 to v3). You can raise this threshold, or even set it to the max: | |
| 136 | + | |
| 137 | +```java | |
| 138 | +poolingOptions | |
| 139 | + .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768) | |
| 140 | + .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000); | |
| 141 | +``` | |
| 142 | + | |
| 143 | +Just keep in mind that high values will give clients more bandwidth and | |
| 144 | +therefore put more pressure on your cluster. This might require some | |
| 145 | +tuning, especially if you have many clients. | |
| 146 | + | |
| 147 | +#### Heartbeat | |
| 148 | + | |
| 149 | +If connections stay idle for too long, they might be dropped by | |
| 150 | +intermediate network devices (routers, firewalls...). Normally, TCP | |
| 151 | +keepalive should take care of this; but tweaking low-level keepalive | |
| 152 | +settings might be impractical in some environments. | |
| 153 | + | |
| 154 | +The driver provides application-side keepalive in the form of a | |
| 155 | +connection heartbeat: when a connection has been idle for a given amount | |
| 156 | +of time, the driver will simulate activity by writing a dummy request to | |
| 157 | +it. | |
| 158 | + | |
| 159 | +This feature is enabled by default. The default heartbeat interval is 30 | |
| 160 | +seconds, it can be customized with the following method: | |
| 161 | + | |
| 162 | +```java | |
| 163 | +poolingOptions.setHeartbeatIntervalSeconds(60); | |
| 164 | +``` | |
| 165 | + | |
| 166 | +If it gets changed at runtime, only connections created after that will | |
| 167 | +use the new interval. Most users will want to do this at startup. | |
| 168 | + | |
| 169 | +The heartbeat interval should be set higher than | |
| 170 | +[SocketOptions.readTimeoutMillis][rtm]: | |
| 171 | +the read timeout is the maximum time that the driver waits for a regular | |
| 172 | +query to complete, therefore the connection should not be considered | |
| 173 | +idle before it has elapsed. | |
| 174 | + | |
| 175 | +To disable heartbeat, set the interval to 0. | |
| 176 | + | |
| 177 | +Implementation note: the dummy request sent by heartbeat is an | |
| 178 | +[OPTIONS](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v3.spec#L278) | |
| 179 | +message. | |
| 180 | + | |
| 181 | + | |
| 182 | +#### Acquisition timeout | |
| 183 | + | |
| 184 | +When the driver tries to send a request to a host, it will first try to | |
| 185 | +acquire a connection from this host's pool. If the pool is busy (i.e. | |
| 186 | +all connections are already handling their maximum number of in flight | |
| 187 | +requests), the client thread will block for a while, until a connection | |
| 188 | +becomes available (note that this will block even if you're using the | |
| 189 | +asynchronous API, like [Session.executeAsync][exec_async]). | |
| 190 | + | |
| 191 | +The time that the driver blocks is controlled by | |
| 192 | +[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection | |
| 193 | +available after this timeout, the driver will try the next host. | |
| 194 | + | |
| 195 | +For some applications, blocking is not acceptable, and it is preferable | |
| 196 | +to fail fast if the request cannot be fulfilled. If that's your case, | |
| 197 | +set the pool timeout to 0. If all hosts are busy, you will get a | |
| 198 | +[NoHostAvailableException][nhae] (if you look at the exception's details, you | |
| 199 | +will see a `java.util.concurrent.TimeoutException` for each host). | |
| 200 | + | |
| 201 | + | |
| 202 | +### Monitoring and tuning the pool | |
| 203 | + | |
| 204 | +The easiest way to monitor pool usage is with [Session.getState][get_state]. Here's | |
| 205 | +a simple example that will print the number of open connections, active | |
| 206 | +requests, and maximum capacity for each host, every 5 seconds: | |
| 207 | + | |
| 208 | +```java | |
| 209 | +final LoadBalancingPolicy loadBalancingPolicy = | |
| 210 | + cluster.getConfiguration().getPolicies().getLoadBalancingPolicy(); | |
| 211 | +final PoolingOptions poolingOptions = | |
| 212 | +cluster.getConfiguration().getPoolingOptions(); | |
| 213 | + | |
| 214 | +ScheduledExecutorService scheduled = | |
| 215 | +Executors.newScheduledThreadPool(1); | |
| 216 | +scheduled.scheduleAtFixedRate(new Runnable() { | |
| 217 | + @Override | |
| 218 | + public void run() { | |
| 219 | + Session.State state = session.getState(); | |
| 220 | + for (Host host : state.getConnectedHosts()) { | |
| 221 | + HostDistance distance = loadBalancingPolicy.distance(host); | |
| 222 | + int connections = state.getOpenConnections(host); | |
| 223 | + int inFlightQueries = state.getInFlightQueries(host); | |
| 224 | + System.out.printf("%s connections=%d, current load=%d, max | |
| 225 | +load=%d%n", | |
| 226 | + host, connections, inFlightQueries, | |
| 227 | + connections * | |
| 228 | +poolingOptions.getMaxRequestsPerConnection(distance)); | |
| 229 | + } | |
| 230 | + } | |
| 231 | +}, 5, 5, TimeUnit.SECONDS); | |
| 232 | +``` | |
| 233 | + | |
| 234 | +In real life, you'll probably want something more sophisticated, like | |
| 235 | +exposing a JMX MBean or sending the data to your favorite monitoring | |
| 236 | +tool. | |
| 237 | + | |
| 238 | +If you find that the current load stays close or equal to the maximum | |
| 239 | +load at all time, it's a sign that your connection pools are saturated | |
| 240 | +and you should raise the max connections per host, or max requests per | |
| 241 | +connection (protocol v3). | |
| 242 | + | |
| 243 | +If you're using protocol v2 and the load is often less than core * 128, | |
| 244 | +your pools are underused and you could get away with less core | |
| 245 | +connections. | |
| 246 | + | |
| 247 | +#### Tuning protocol v3 for very high throughputs | |
| 248 | + | |
| 249 | +As mentioned above, the default pool size for protocol v3 is core = max | |
| 250 | += 1. This means all requests to a given node will share a single | |
| 251 | +connection, and therefore a single Netty I/O thread. | |
| 252 | + | |
| 253 | +There is a corner case where this I/O thread can max out its CPU core | |
| 254 | +and become a bottleneck in the driver; in our benchmarks, this happened | |
| 255 | +with a single-node cluster and a high throughput (approximately 80K | |
| 256 | +requests / second). | |
| 257 | + | |
| 258 | +It's unlikely that you'll run into this issue: in most real-world | |
| 259 | +deployments, the driver connects to more than one node, so the load will | |
| 260 | +spread across more I/O threads. However if you suspect that you | |
| 261 | +experience the issue, here's what to look out for: | |
| 262 | + | |
| 263 | +* the driver throughput plateaus but the process does not appear to | |
| 264 | + max out any system resource (in particular, overall CPU usage is well | |
| 265 | + below 100%); | |
| 266 | +* one of the driver's I/O threads maxes out its CPU core. You can see | |
| 267 | + that with a profiler, or OS-level tools like `pidstat -tu` on Linux. | |
| 268 | + I/O threads are called `<cluster_name>-nio-worker-<n>`, unless you're | |
| 269 | + injecting your own `EventLoopGroup` with `NettyOptions`. | |
| 270 | + | |
| 271 | +The solution is to add more connections per node. To ensure that | |
| 272 | +additional connections get created before you run into the bottleneck, | |
| 273 | +either: | |
| 274 | + | |
| 275 | +* set core = max; | |
| 276 | +* keep core = 1, but adjust [maxRequestsPerConnection][mrpc] and | |
| 277 | + [newConnectionThreshold][nct] so that enough connections are added by | |
| 278 | + the time you reach the bottleneck. | |
| 279 | + | |
| 280 | +[result_set_future]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSetFuture.html | |
| 281 | +[pooling_options]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html | |
| 282 | +[lbp]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 283 | +[nct]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int) | |
| 284 | +[mrpc]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int) | |
| 285 | +[sits]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds(int) | |
| 286 | +[rtm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis() | |
| 287 | +[exec_async]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement) | |
| 288 | +[ptm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 289 | +[nhae]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 290 | +[get_state]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#getState() |
added manual/query_timestamps/README.md +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +## Query timestamps | |
| 2 | + | |
| 3 | +In Cassandra, each mutation has a microsecond-precision timestamp, which | |
| 4 | +is used to order operations relative to each other. | |
| 5 | + | |
| 6 | +There are various ways to assign it: | |
| 7 | + | |
| 8 | +### Server-side generation | |
| 9 | + | |
| 10 | +If the client does not specify any timestamp, the server will assign one | |
| 11 | +based on the time it receives the query. | |
| 12 | + | |
| 13 | +This can be a problem when the order of the writes matter: with unlucky | |
| 14 | +timing (different coordinators, network latency, etc.), two successive | |
| 15 | +requests from the same client might be processed in a different order | |
| 16 | +server-side, and end up with out-of-order timestamps. | |
| 17 | + | |
| 18 | +### CQL `USING TIMESTAMP` | |
| 19 | + | |
| 20 | +You can explicitly provide the timestamp in your CQL query: | |
| 21 | + | |
| 22 | +```java | |
| 23 | +session.execute("INSERT INTO my_table(c1, c2) values (1, 1) " + | |
| 24 | + "USING TIMESTAMP 1432815430948040"); | |
| 25 | +``` | |
| 26 | + | |
| 27 | +This solves the problems of server-side generation: the client has | |
| 28 | +control over the ordering of the statements it generates. On the other | |
| 29 | +hand, it puts the burden of generating timestamps on client code. | |
| 30 | + | |
| 31 | +### Client-side generation | |
| 32 | + | |
| 33 | +Starting with version 2.1.2 of the driver, and if [native | |
| 34 | +protocol](../native_protocol/) v3 or above is in use, a *default | |
| 35 | +timestamp* can be sent with each query. | |
| 36 | + | |
| 37 | +To enable this feature, provide an instance of [TimestampGenerator][tsg] | |
| 38 | +at initialization: | |
| 39 | + | |
| 40 | +```java | |
| 41 | +Cluster.builder().addContactPoint("127.0.0.1") | |
| 42 | + .withTimestampGenerator(new AtomicMonotonicTimestampGenerator()) | |
| 43 | + .build(); | |
| 44 | +``` | |
| 45 | + | |
| 46 | +The default is still server-side generation. So unless you explicitly | |
| 47 | +provide a generator, you get the same behavior as previous driver | |
| 48 | +versions. | |
| 49 | + | |
| 50 | +In addition, you can also override the default timestamp on a | |
| 51 | +per-statement basis: | |
| 52 | + | |
| 53 | +```java | |
| 54 | +Statement statement = new SimpleStatement( | |
| 55 | + "UPDATE users SET email = 'x@y.com' where id = 1"); | |
| 56 | +statement.setDefaultTimestamp(1234567890); | |
| 57 | +session.execute(statement); | |
| 58 | +``` | |
| 59 | + | |
| 60 | +[tsg]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/TimestampGenerator.html | |
| 61 | + | |
| 62 | +### Summary | |
| 63 | + | |
| 64 | +As shown in the previous sections, there are multiple ways to provide a | |
| 65 | +timestamp, some of which overlap. The order of precedence is the | |
| 66 | +following: | |
| 67 | + | |
| 68 | +1. if there is a `USING TIMESTAMP` clause in the CQL string, use that | |
| 69 | + over anything else; | |
| 70 | +2. otherwise, if a default timestamp was set on the statement and is | |
| 71 | + different from `Long.MIN_VALUE`, use it; | |
| 72 | +3. otherwise, if a generator is specified, invoke it and use its result | |
| 73 | + if it is different from `Long.MIN_VALUE`; | |
| 74 | +4. otherwise, let the server assign the timestamp. | |
| 75 | + | |
| 76 | +Steps 2 and 3 only apply if native protocol v3 or above is in use. |
added manual/shaded_jar/README.md +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +## Using the shaded JAR | |
| 2 | + | |
| 3 | +The default driver JAR depends on [Netty](http://netty.io/), which is | |
| 4 | +used internally for networking. | |
| 5 | + | |
| 6 | +This explicit dependency can be a problem if your application already | |
| 7 | +uses another Netty version. To avoid conflicts, we provide a "shaded" | |
| 8 | +version of the JAR, which bundles the Netty classes under a different | |
| 9 | +package name: | |
| 10 | + | |
| 11 | +```xml | |
| 12 | +<dependency> | |
| 13 | + <groupId>com.datastax.cassandra</groupId> | |
| 14 | + <artifactId>cassandra-driver-core</artifactId> | |
| 15 | + <version>2.1.9</version> | |
| 16 | + <classifier>shaded</classifier> | |
| 17 | + <!-- Because the shaded JAR uses the original POM, you still need | |
| 18 | + to exclude this dependency explicitly: --> | |
| 19 | + <exclusions> | |
| 20 | + <exclusion> | |
| 21 | + <groupId>io.netty</groupId> | |
| 22 | + <artifactId>*</artifactId> | |
| 23 | + </exclusion> | |
| 24 | + </exclusions> | |
| 25 | +</dependency> | |
| 26 | +``` | |
| 27 | + | |
| 28 | +If you also use the mapper, you need to remove its dependency to the | |
| 29 | +non-shaded JAR: | |
| 30 | + | |
| 31 | +```xml | |
| 32 | +<dependency> | |
| 33 | + <groupId>com.datastax.cassandra</groupId> | |
| 34 | + <artifactId>cassandra-driver-core</artifactId> | |
| 35 | + <version>2.1.9</version> | |
| 36 | + <classifier>shaded</classifier> | |
| 37 | + <exclusions> | |
| 38 | + <exclusion> | |
| 39 | + <groupId>io.netty</groupId> | |
| 40 | + <artifactId>*</artifactId> | |
| 41 | + </exclusion> | |
| 42 | + </exclusions> | |
| 43 | +</dependency> | |
| 44 | +<dependency> | |
| 45 | + <groupId>com.datastax.cassandra</groupId> | |
| 46 | + <artifactId>cassandra-driver-mapping</artifactId> | |
| 47 | + <version>2.1.9</version> | |
| 48 | + <exclusions> | |
| 49 | + <exclusion> | |
| 50 | + <groupId>com.datastax.cassandra</groupId> | |
| 51 | + <artifactId>cassandra-driver-core</artifactId> | |
| 52 | + </exclusion> | |
| 53 | + </exclusions> | |
| 54 | +</dependency> | |
| 55 | +``` |
added manual/speculative_execution/README.md +343 −0
| @@ -0,0 +1,343 @@ | ||
| 1 | +## Speculative query execution | |
| 2 | + | |
| 3 | +Sometimes a Cassandra node might be experiencing difficulties (ex: long | |
| 4 | +GC pause) and take longer than usual to reply. Queries sent to that node | |
| 5 | +will experience bad latency. | |
| 6 | + | |
| 7 | +One thing we can do to improve that is pre-emptively start a second | |
| 8 | +execution of the query against another node, before the first node has | |
| 9 | +replied or errored out. If that second node replies faster, we can send | |
| 10 | +the response back to the client (we also cancel the first query): | |
| 11 | + | |
| 12 | +```ditaa | |
| 13 | +client driver exec1 exec2 | |
| 14 | +--+----------------+--------------+------+--- | |
| 15 | + | execute(query) | | |
| 16 | + |--------------->| | |
| 17 | + | | query host1 | |
| 18 | + | |------------->| | |
| 19 | + | | | | |
| 20 | + | | | | |
| 21 | + | | query host2 | |
| 22 | + | |-------------------->| | |
| 23 | + | | | | | |
| 24 | + | | | | | |
| 25 | + | | host2 replies | | |
| 26 | + | |<--------------------| | |
| 27 | + | complete | | | |
| 28 | + |<---------------| | | |
| 29 | + | | cancel | | |
| 30 | + | |------------->| | |
| 31 | +``` | |
| 32 | + | |
| 33 | +Or the first node could reply just after the second execution was | |
| 34 | +started. In this case, we cancel the second execution. In other words, | |
| 35 | +whichever node replies faster "wins" and completes the client query: | |
| 36 | + | |
| 37 | +```ditaa | |
| 38 | +client driver exec1 exec2 | |
| 39 | +--+----------------+--------------+------+--- | |
| 40 | + | execute(query) | | |
| 41 | + |--------------->| | |
| 42 | + | | query host1 | |
| 43 | + | |------------->| | |
| 44 | + | | | | |
| 45 | + | | | | |
| 46 | + | | query host2 | |
| 47 | + | |-------------------->| | |
| 48 | + | | | | | |
| 49 | + | | | | | |
| 50 | + | | host1 replies| | | |
| 51 | + | |<-------------| | | |
| 52 | + | complete | | | |
| 53 | + |<---------------| | | |
| 54 | + | | cancel | | |
| 55 | + | |-------------------->| | |
| 56 | +``` | |
| 57 | + | |
| 58 | +Speculative executions are **disabled** by default. The following | |
| 59 | +sections cover the practical details and how to enable them. | |
| 60 | + | |
| 61 | +### Query idempotence | |
| 62 | + | |
| 63 | +One important aspect to consider is whether queries are idempotent, i.e. | |
| 64 | +whether they can be applied multiple times without changing the result | |
| 65 | +beyond the initial application. **If a query is not idempotent, the | |
| 66 | +driver will never schedule speculative executions for it**, because | |
| 67 | +there is no way to guarantee that only one node will apply the mutation. | |
| 68 | + | |
| 69 | +As of Cassandra 2.1.4, the only queries that are *not* idempotent are: | |
| 70 | + | |
| 71 | +* counter operations; | |
| 72 | +* prepending or appending to a list column; | |
| 73 | +* using non-idempotent CQL functions, like `now()` or `uuid()`. | |
| 74 | + | |
| 75 | +In the driver, this is determined by | |
| 76 | +[Statement#isIdempotent()][isIdempotent]. Unfortunately, the driver | |
| 77 | +doesn't parse query strings, so in most cases it has no information | |
| 78 | +about what the query actually does. Therefore: | |
| 79 | + | |
| 80 | +* **`Statement#isIdempotent()` is only computed automatically for | |
| 81 | + statements built with [QueryBuilder][QueryBuilder]**. | |
| 82 | + Note that the driver takes a rather conservative approach with uses | |
| 83 | + of `fcall()` or `raw()`: whenever they appear in a value to be | |
| 84 | + inserted in the database (like the values of an `Insert` or the | |
| 85 | + right-hand side of an assignment in an `Update`), the statement | |
| 86 | + will be considered non-idempotent by default. If you know that your | |
| 87 | + CQL functions or expressions are safe, force idempotence to `true` | |
| 88 | + on the statement manually (see below); | |
| 89 | +* **for all other types of statements, it defaults to `false`.** You'll | |
| 90 | + need to set it manually, with one of the mechanism described below. | |
| 91 | + | |
| 92 | +You can override the value on each statement: | |
| 93 | + | |
| 94 | +```java | |
| 95 | +Statement s = new SimpleStatement("SELECT * FROM users WHERE id = 1"); | |
| 96 | +s.setIdempotent(true); | |
| 97 | +``` | |
| 98 | + | |
| 99 | +Note that this will also work for built statements (and override the | |
| 100 | +computed value). | |
| 101 | + | |
| 102 | +Additionally, if you know for a fact that your application does not use | |
| 103 | +any of the non-idempotent CQL queries listed above, you can change the | |
| 104 | +default cluster-wide: | |
| 105 | + | |
| 106 | +```java | |
| 107 | +// Make all statements idempotent by default: | |
| 108 | +cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(true); | |
| 109 | +``` | |
| 110 | + | |
| 111 | +[isIdempotent]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html#isIdempotent() | |
| 112 | +[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 113 | + | |
| 114 | +### Enabling speculative executions | |
| 115 | + | |
| 116 | +Speculative executions are controlled by an instance of | |
| 117 | +[SpeculativeExecutionPolicy][sep] provided when initializing the | |
| 118 | +`Cluster`. This policy defines the threshold after which a new | |
| 119 | +speculative execution will be triggered. | |
| 120 | + | |
| 121 | +[sep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html | |
| 122 | + | |
| 123 | +Two implementations are provided with the driver: | |
| 124 | + | |
| 125 | +#### [ConstantSpeculativeExecutionPolicy][csep] | |
| 126 | + | |
| 127 | +This simple policy uses a constant threshold: | |
| 128 | + | |
| 129 | +```java | |
| 130 | +Cluster cluster = Cluster.builder() | |
| 131 | + .addContactPoint("127.0.0.1") | |
| 132 | + .withSpeculativeExecutionPolicy( | |
| 133 | + new ConstantSpeculativeExecutionPolicy( | |
| 134 | + 500, // delay before a new execution is launched | |
| 135 | + 2 // maximum number of executions | |
| 136 | + )) | |
| 137 | + .build(); | |
| 138 | +``` | |
| 139 | + | |
| 140 | +Given the above configuration, an idempotent query would be handled this | |
| 141 | +way: | |
| 142 | + | |
| 143 | +* start the initial execution at t0; | |
| 144 | +* if no response has been received at t0 + 500 milliseconds, start a | |
| 145 | + speculative execution on another node; | |
| 146 | +* if no response has been received at t0 + 1000 milliseconds, start | |
| 147 | + another speculative execution on a third node. | |
| 148 | + | |
| 149 | +[csep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/ConstantSpeculativeExecutionPolicy.html | |
| 150 | + | |
| 151 | +#### [PercentileSpeculativeExecutionPolicy][psep] | |
| 152 | + | |
| 153 | +This policy sets the threshold at a given latency percentile for the | |
| 154 | +current host, based on recent statistics. | |
| 155 | + | |
| 156 | +**As of 2.1.6, this class is provided as a beta preview: it hasn't been | |
| 157 | +extensively tested yet, and the API is still subject to change.** | |
| 158 | + | |
| 159 | +First and foremost, make sure that the [HdrHistogram][hdr] library (used | |
| 160 | +under the hood to collect latencies) is in your classpath. It's defined | |
| 161 | +as an optional dependency in the driver's POM, so you'll need to | |
| 162 | +explicitly depend on it: | |
| 163 | + | |
| 164 | +```xml | |
| 165 | +<dependency> | |
| 166 | + <groupId>org.hdrhistogram</groupId> | |
| 167 | + <artifactId>HdrHistogram</artifactId> | |
| 168 | + <version>2.1.4</version> | |
| 169 | +</dependency> | |
| 170 | +``` | |
| 171 | + | |
| 172 | +Then create an instance of [PerHostPercentileTracker][phpt] that will collect | |
| 173 | +latency statistics for your `Cluster`: | |
| 174 | + | |
| 175 | +```java | |
| 176 | +// There are more options than shown here, please refer to the API docs | |
| 177 | +// for more information | |
| 178 | +PerHostPercentileTracker tracker = PerHostPercentileTracker | |
| 179 | + .builderWithHighestTrackableLatencyMillis(15000) | |
| 180 | + .build(); | |
| 181 | +``` | |
| 182 | + | |
| 183 | +Create an instance of the policy with the tracker, and pass it to your | |
| 184 | +cluster: | |
| 185 | + | |
| 186 | +```java | |
| 187 | +PercentileSpeculativeExecutionPolicy policy = | |
| 188 | + new PercentileSpeculativeExecutionPolicy( | |
| 189 | + tracker, | |
| 190 | + 99.0, // percentile | |
| 191 | + 2); // maximum number of executions | |
| 192 | + | |
| 193 | +Cluster cluster = Cluster.builder() | |
| 194 | + .addContactPoint("127.0.0.1") | |
| 195 | + .withSpeculativeExecutionPolicy(policy) | |
| 196 | + .build(); | |
| 197 | +``` | |
| 198 | + | |
| 199 | +Finally, don't forget to register your tracker with the cluster (the | |
| 200 | +policy does not do this itself): | |
| 201 | + | |
| 202 | +```java | |
| 203 | +cluster.register(tracker); | |
| 204 | +``` | |
| 205 | + | |
| 206 | +Note that `PerHostPercentileTracker` may also be used with a slow query | |
| 207 | +logger (see the [Logging](../logging/) section). In that case, you would | |
| 208 | +create a single tracker object and share it with both components. | |
| 209 | + | |
| 210 | +[psep]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/PercentileSpeculativeExecutionPolicy.html | |
| 211 | +[hdr]: http://hdrhistogram.github.io/HdrHistogram/ | |
| 212 | +[phpt]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PerHostPercentileTracker.html | |
| 213 | + | |
| 214 | +#### Using your own | |
| 215 | + | |
| 216 | +As with all policies, you are free to provide your own by implementing | |
| 217 | +`SpeculativeExecutionPolicy`. | |
| 218 | + | |
| 219 | +### How speculative executions affect retries | |
| 220 | + | |
| 221 | +Regardless of speculative executions, the driver has a retry mechanism: | |
| 222 | + | |
| 223 | +* on an internal error, it will try the next host; | |
| 224 | +* when the consistency level could not be reached (`unavailable` error | |
| 225 | + or read or write timeout), it will delegate the decision to | |
| 226 | + [RetryPolicy][retry_policy], which might trigger a retry on the same | |
| 227 | + host. | |
| 228 | + | |
| 229 | +Turning speculative executions on doesn't change this behavior. Each | |
| 230 | +parallel execution will trigger retries independently: | |
| 231 | + | |
| 232 | +```ditaa | |
| 233 | +client driver exec1 exec2 | |
| 234 | +--+----------------+--------------+------+--- | |
| 235 | + | execute(query) | | |
| 236 | + |--------------->| | |
| 237 | + | | query host1 | |
| 238 | + | |------------->| | |
| 239 | + | | | | |
| 240 | + | | unavailable | | |
| 241 | + | |<-------------| | |
| 242 | + | | | |
| 243 | + | |retry at lower CL | |
| 244 | + | |------------->| | |
| 245 | + | | | | |
| 246 | + | | query host2 | |
| 247 | + | |-------------------->| | |
| 248 | + | | | | | |
| 249 | + | | server error | | |
| 250 | + | |<--------------------| | |
| 251 | + | | | | |
| 252 | + | | retry on host3 | |
| 253 | + | |-------------------->| | |
| 254 | + | | | | | |
| 255 | + | | host1 replies| | | |
| 256 | + | |<-------------| | | |
| 257 | + | complete | | | |
| 258 | + |<---------------| | | |
| 259 | + | | cancel | | |
| 260 | + | |-------------------->| | |
| 261 | +``` | |
| 262 | + | |
| 263 | +The only impact is that all executions of the same query always share | |
| 264 | +the same query plan, so each host will be used by at most one execution. | |
| 265 | + | |
| 266 | +[retry_policy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html | |
| 267 | + | |
| 268 | +### Tuning and practical details | |
| 269 | + | |
| 270 | +The goal of speculative executions is to improve overall latency (the | |
| 271 | +time between `execute(query)` and `complete` in the diagrams above) at | |
| 272 | +high percentiles. On the flipside, they cause the driver to send more | |
| 273 | +individual requests, so throughput will not necessarily improve. | |
| 274 | + | |
| 275 | +You can monitor how many speculative executions were triggered with the | |
| 276 | +`speculative-executions` metric (exposed in the Java API as | |
| 277 | +[cluster.getMetrics().getErrors().getSpeculativeExecutions()][se_metric]). | |
| 278 | +It should only be a few percents of the total number of requests | |
| 279 | +([cluster.getMetrics().getRequestsTimer().getCount()][request_metric]). | |
| 280 | + | |
| 281 | +[se_metric]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metrics.Errors.html#getSpeculativeExecutions() | |
| 282 | +[request_metric]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Metrics.html#getRequestsTimer() | |
| 283 | + | |
| 284 | +#### Stream id exhaustion | |
| 285 | + | |
| 286 | +One side-effect of speculative executions is that many requests are | |
| 287 | +cancelled, which can lead to a phenomenon called *stream id exhaustion*: | |
| 288 | +each TCP connection can handle multiple simultaneous requests, | |
| 289 | +identified by a unique number called *stream id*. When a request gets | |
| 290 | +cancelled, we can't reuse its stream id immediately because we might | |
| 291 | +still receive a response from the server later. If this happens often, | |
| 292 | +the number of available stream ids diminishes over time, and when it | |
| 293 | +goes below a given threshold we close the connection and create a new | |
| 294 | +one. If requests are often cancelled, so will see connections being | |
| 295 | +recycled at a high rate. | |
| 296 | + | |
| 297 | +One way to detect this is to monitor open connections per host | |
| 298 | +([Session.getState().getOpenConnections(host)][session_state]) against | |
| 299 | +TCP connections at the OS level. If open connections stay constant but | |
| 300 | +you see many TCP connections in closing states, you might be running | |
| 301 | +into this issue. Try raising the speculative execution threshold. | |
| 302 | + | |
| 303 | +This problem is more likely to happen with version 2 of the native | |
| 304 | +protocol, because each TCP connection only has 128 stream ids. With | |
| 305 | +version 3 (driver 2.1.2 or above with Cassandra 2.1 or above), there are | |
| 306 | +32K stream ids per connection, so higher cancellation rates can be | |
| 307 | +sustained. If you're unsure of which native protocol version you're | |
| 308 | +using, you can check with | |
| 309 | +[cluster.getConfiguration().getProtocolOptions().getProtocolVersion()][protocol_version]. | |
| 310 | + | |
| 311 | +[session_state]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.State.html | |
| 312 | +[protocol_version]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ProtocolOptions.html#getProtocolVersion() | |
| 313 | + | |
| 314 | +#### Request ordering and client timestamps | |
| 315 | + | |
| 316 | +Another issue that might arise is that you get unintuitive results | |
| 317 | +because of request ordering. Suppose you run the following query with | |
| 318 | +speculative executions enabled: | |
| 319 | + | |
| 320 | + insert into my_table (k, v) values (1, 1); | |
| 321 | + | |
| 322 | +The first execution is a bit too slow, so a second execution gets | |
| 323 | +triggered. Finally, the first execution completes, so the client code | |
| 324 | +gets back an acknowledgement, and the second execution is cancelled. | |
| 325 | +However, cancelling only means that the driver stops waiting for the | |
| 326 | +server's response, the request could still be "on the wire"; let's | |
| 327 | +assume that this is the case. | |
| 328 | + | |
| 329 | +Now you run the following query, which completes successfully: | |
| 330 | + | |
| 331 | + delete from my_table where k = 1; | |
| 332 | + | |
| 333 | +But now the second execution of the first query finally reaches its | |
| 334 | +target node, which applies the mutation. The row that you've just | |
| 335 | +deleted is back! | |
| 336 | + | |
| 337 | +The workaround is to use a timestamp with your queries: | |
| 338 | + | |
| 339 | + insert into my_table (k, v) values (1, 1) USING TIMESTAMP 1432764000; | |
| 340 | + | |
| 341 | +If you're using native protocol v3, you can also enable [client-side | |
| 342 | +timestamps](../query_timestamps/#client-side-generation) to have this done | |
| 343 | +automatically. |
added manual/ssl/README.md +180 −0
| @@ -0,0 +1,180 @@ | ||
| 1 | +## SSL | |
| 2 | + | |
| 3 | +You can secure traffic between the driver and Cassandra with SSL. There | |
| 4 | +are two aspects to that: | |
| 5 | + | |
| 6 | +* **client-to-node encryption**, where the traffic is encrypted, and the | |
| 7 | + client verifies the identity of the Cassandra nodes it connects to; | |
| 8 | +* optionally, **client certificate authentication**, where Cassandra | |
| 9 | + nodes also verify the identity of the client. | |
| 10 | + | |
| 11 | +This section describes the driver-side configuration; it assumes that | |
| 12 | +you've already configured SSL in Cassandra: | |
| 13 | + | |
| 14 | +* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html) | |
| 15 | + covers a basic approach with self-signed certificates, which is fine | |
| 16 | + for development and tests. | |
| 17 | +* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html) | |
| 18 | + details a more advanced solution based on a Certificate Authority | |
| 19 | + (CA). | |
| 20 | + | |
| 21 | +### Preparing the certificates | |
| 22 | + | |
| 23 | +#### Client truststore | |
| 24 | + | |
| 25 | +This is required for client-to-node encryption. | |
| 26 | + | |
| 27 | +If you're using self-signed certificates, you need to export the public | |
| 28 | +part of each node's certificate from that node's keystore: | |
| 29 | + | |
| 30 | +``` | |
| 31 | +keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore | |
| 32 | +``` | |
| 33 | + | |
| 34 | +Then add all public certificates to the client truststore: | |
| 35 | + | |
| 36 | +``` | |
| 37 | +keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore | |
| 38 | +keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore | |
| 39 | +... | |
| 40 | +``` | |
| 41 | + | |
| 42 | +If you're using a Certificate Authority, the client truststore only | |
| 43 | +needs to contain the CA's certificate: | |
| 44 | + | |
| 45 | +``` | |
| 46 | +keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore | |
| 47 | +``` | |
| 48 | + | |
| 49 | +#### Client keystore | |
| 50 | + | |
| 51 | +If you also intend to use client certificate authentication, generate | |
| 52 | +the public and private key pair for the client: | |
| 53 | + | |
| 54 | +``` | |
| 55 | +keytool -genkey -keyalg RSA -alias client -keystore client.keystore | |
| 56 | +``` | |
| 57 | + | |
| 58 | +If you're using self-signed certificates, extract the public part of the | |
| 59 | +client certificate, and import it in the truststore of each Cassandra | |
| 60 | +node: | |
| 61 | + | |
| 62 | +``` | |
| 63 | +keytool -export -alias client -file client.cer -keystore client.keystore | |
| 64 | +keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore | |
| 65 | +``` | |
| 66 | + | |
| 67 | +If you're using a CA, sign the client certificate with it (see the blog | |
| 68 | +post linked at the top of this page). Then the nodes' truststores only | |
| 69 | +need to contain the CA's certificate (which should already be the case | |
| 70 | +if you've followed the steps for inter-node encryption). | |
| 71 | + | |
| 72 | +### Driver configuration | |
| 73 | + | |
| 74 | +#### Property-based | |
| 75 | + | |
| 76 | +`withSSL()` gives you a basic JSSE configuration: | |
| 77 | + | |
| 78 | +```java | |
| 79 | +Cluster cluster = Cluster.builder() | |
| 80 | + .addContactPoint("127.0.0.1") | |
| 81 | + .withSSL() | |
| 82 | + .build(); | |
| 83 | +``` | |
| 84 | + | |
| 85 | +You can then use | |
| 86 | +[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization) | |
| 87 | +for specific details, like keystore locations and passwords: | |
| 88 | + | |
| 89 | +``` | |
| 90 | +-Djavax.net.ssl.trustStore=/path/to/client.truststore | |
| 91 | +-Djavax.net.ssl.trustStorePassword=password123 | |
| 92 | +# If you're using client authentication: | |
| 93 | +-Djavax.net.ssl.keyStore=/path/to/client.keystore | |
| 94 | +-Djavax.net.ssl.keyStorePassword=password123 | |
| 95 | +``` | |
| 96 | + | |
| 97 | +#### Programmatic | |
| 98 | + | |
| 99 | +If you need more control than what system properties allow, you can | |
| 100 | +configure SSL programmatically by creating an [SSLOptions] instance: | |
| 101 | + | |
| 102 | +```java | |
| 103 | +SSLContext sslContext = ... // create and configure SSL context | |
| 104 | +String[] cipherSuites = ... | |
| 105 | + | |
| 106 | +SSLOptions sslOptions = new SSLOptions(sslContext, cipherSuites); | |
| 107 | + | |
| 108 | +Cluster cluster = Cluster.builder() | |
| 109 | + .addContactPoint("127.0.0.1") | |
| 110 | + .withSSL(sslOptions) | |
| 111 | + .build(); | |
| 112 | +``` | |
| 113 | + | |
| 114 | +A known limitation of the current API is that you can't customize the | |
| 115 | +`SSLEngine`, which prevents advanced features like hostname | |
| 116 | +verification. This will be fixed in 3.0 (see | |
| 117 | +[JAVA-841](https://datastax-oss.atlassian.net/browse/JAVA-841)), in the | |
| 118 | +meantime see below for a workaround. | |
| 119 | + | |
| 120 | + | |
| 121 | +### Bypassing `SSLOptions` | |
| 122 | + | |
| 123 | +For advanced use cases, it's possible to bypass `SSLOptions` entirely: | |
| 124 | +since the driver provides a hook into the Netty pipeline (by way of | |
| 125 | +[NettyOptions]), you can add the SSL handler yourself: | |
| 126 | + | |
| 127 | +```java | |
| 128 | +import io.netty.handler.ssl.SslHandler; | |
| 129 | +import javax.net.ssl.SSLContext; | |
| 130 | +import javax.net.ssl.SSLEngine; | |
| 131 | + | |
| 132 | +// Base implementation: each time a connection is established, create an SSL handler | |
| 133 | +// and add it to the pipeline: | |
| 134 | +public abstract class SslNettyOptions extends NettyOptions { | |
| 135 | + @Override | |
| 136 | + public void afterChannelInitialized(SocketChannel channel) throws Exception { | |
| 137 | + channel.pipeline().addFirst("ssl", createSslHandler(channel)); | |
| 138 | + } | |
| 139 | + | |
| 140 | + protected abstract SslHandler createSslHandler(SocketChannel channel); | |
| 141 | +} | |
| 142 | + | |
| 143 | +// Concrete implementation based on JSSE | |
| 144 | +public class MyNettyOptions extends SslNettyOptions { | |
| 145 | + | |
| 146 | + private final SSLContext sslContext = createContext(); | |
| 147 | + | |
| 148 | + protected SslHandler createSslHandler(SocketChannel channel) { | |
| 149 | + return new SslHandler(createEngine(sslContext, channel)); | |
| 150 | + } | |
| 151 | + | |
| 152 | + private static SSLContext createContext() { | |
| 153 | + ... // create and configure context | |
| 154 | + } | |
| 155 | + | |
| 156 | + private static SSLEngine createEngine(SSLContext sslContext, SocketChannel channel) { | |
| 157 | + SSLEngine engine = sslContext.createSSLEngine(); | |
| 158 | + engine.setUseClientMode(true); | |
| 159 | + ... // any extra configuration | |
| 160 | + return engine; | |
| 161 | + } | |
| 162 | +} | |
| 163 | + | |
| 164 | +cluster = Cluster.builder() | |
| 165 | + .addContactPoint("127.0.0.1") | |
| 166 | + .withNettyOptions(new MyNettyOptions()) | |
| 167 | + .build(); | |
| 168 | +``` | |
| 169 | + | |
| 170 | +This could be used for the following use cases: | |
| 171 | + | |
| 172 | +* fine control over JSSE configuration, for example tuning the SSL | |
| 173 | + engine for hostname verification; | |
| 174 | +* bypassing JSSE altogether in favor of another SSL implementation: | |
| 175 | + recent Netty versions support | |
| 176 | + [OpenSSL](http://netty.io/wiki/forked-tomcat-native.html) | |
| 177 | + for improved performance. | |
| 178 | + | |
| 179 | +[SSLOptions]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SSLOptions.html | |
| 180 | +[NettyOptions]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/NettyOptions.html |
added manual/statements/README.md +54 −0
| @@ -0,0 +1,54 @@ | ||
| 1 | +## Statements | |
| 2 | + | |
| 3 | +To execute a query, you create a [Statement] instance and pass it to | |
| 4 | +`Session#execute()`. The driver provides various implementations: | |
| 5 | + | |
| 6 | +* [SimpleStatement]: a simple implementation built directly from a | |
| 7 | + character string. Typically used for queries that are executed only | |
| 8 | + once or a few times. | |
| 9 | +* [BoundStatement]: obtained by binding values to a [prepared | |
| 10 | + statement](prepared/). Typically used for queries that are executed | |
| 11 | + often, with different values. | |
| 12 | +* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It | |
| 13 | + can be executed directly like a simple statement, or prepared. | |
| 14 | +* [BatchStatement]: a statement that groups multiple statements to be | |
| 15 | + executed as a batch. | |
| 16 | + | |
| 17 | +`Session` also has a shortcut to build and execute a simple statement in | |
| 18 | +a single call: | |
| 19 | + | |
| 20 | +```java | |
| 21 | +session.execute("select release_version from system.local"); | |
| 22 | + | |
| 23 | +// Is equivalent to: | |
| 24 | +Statement s = new SimpleStatement("select release_version from system.local"); | |
| 25 | +session.execute(s); | |
| 26 | +``` | |
| 27 | + | |
| 28 | +### Customizing execution | |
| 29 | + | |
| 30 | +Before executing a statement, you might want to customize certain | |
| 31 | +aspects of its execution. `Statement` provides a number of methods for | |
| 32 | +this, for example: | |
| 33 | + | |
| 34 | +```java | |
| 35 | +Statement s = new SimpleStatement("select release_version from system.local"); | |
| 36 | +s.enableTracing(); | |
| 37 | +session.execute(s); | |
| 38 | +``` | |
| 39 | + | |
| 40 | +If you use custom policies ([RetryPolicy], [LoadBalancingPolicy], | |
| 41 | +[SpeculativeExecutionPolicy]...), you might also want to have custom | |
| 42 | +properties that influence statement execution. To achieve this, you can | |
| 43 | +wrap your statements in a custom [StatementWrapper] implementation. | |
| 44 | + | |
| 45 | +[Statement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html | |
| 46 | +[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html | |
| 47 | +[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html | |
| 48 | +[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html | |
| 49 | +[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 50 | +[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/BuiltStatement.html | |
| 51 | +[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/StatementWrapper.html | |
| 52 | +[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html | |
| 53 | +[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 54 | +[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html |
added manual/statements/prepared/README.md +172 −0
| @@ -0,0 +1,172 @@ | ||
| 1 | +## Prepared statements | |
| 2 | + | |
| 3 | +When Cassandra executes a query, the first thing it does is parse the | |
| 4 | +query string to an internal representation. If the same query is used | |
| 5 | +often, you can use a prepared statement, which allows Cassandra to cache | |
| 6 | +that representation, and save time and resources for subsequent | |
| 7 | +executions. Prepared statements are typically parameterized, using | |
| 8 | +different values for each execution: | |
| 9 | + | |
| 10 | +```java | |
| 11 | +PreparedStatement prepared = session.prepare( | |
| 12 | + "insert into product (sku, description) values (?, ?)"); | |
| 13 | + | |
| 14 | +BoundStatement bound; | |
| 15 | + | |
| 16 | +bound = prepared.bind("234827", "Mouse"); | |
| 17 | +session.execute(bound); | |
| 18 | + | |
| 19 | +bound = prepared.bind("987274", "Keyboard"); | |
| 20 | +session.execute(bound); | |
| 21 | +``` | |
| 22 | + | |
| 23 | +Statements should be be prepared only once. If you call `prepare` | |
| 24 | +multiple times with the same query string, the driver will log a | |
| 25 | +warning. So your application should cache the `PreparedStatement` object | |
| 26 | +once it's been created (this can be as simple as storing it as a field | |
| 27 | +in a DAO). | |
| 28 | + | |
| 29 | +### Parameters and binding | |
| 30 | + | |
| 31 | +Parameters can be either anonymous or named (named parameters are only | |
| 32 | +available with [native protocol](../../native_protocol) v2 or above): | |
| 33 | + | |
| 34 | +```java | |
| 35 | +ps1 = session.prepare("insert into product (sku, description) values (?, ?)"); | |
| 36 | +ps2 = session.prepare("insert into product (sku, description) values (:s, :d)"); | |
| 37 | +``` | |
| 38 | + | |
| 39 | +To turn the statement into its executable form, you need to *bind* it | |
| 40 | +and provide values for the parameters. As shown previously, there is a | |
| 41 | +shorthand form to do it all in one call: | |
| 42 | + | |
| 43 | +```java | |
| 44 | +BoundStatement bound = ps1.bind("324378", "LCD screen"); | |
| 45 | +``` | |
| 46 | + | |
| 47 | +You can also bind first, then use setters, which is slightly more | |
| 48 | +explicit: | |
| 49 | + | |
| 50 | +```java | |
| 51 | +// Positional setters: | |
| 52 | +BoundStatement bound = ps1.bind() | |
| 53 | + .setString(0, "324378") | |
| 54 | + .setString(1, "LCD screen"); | |
| 55 | + | |
| 56 | +// Named setters: | |
| 57 | +BoundStatement bound = ps2.bind() | |
| 58 | + .setString("s", "324378") | |
| 59 | + .setString("d", "LCD screen"); | |
| 60 | +``` | |
| 61 | + | |
| 62 | +If you don't set a parameter, it is sent as `null` (note that this | |
| 63 | +behavior changes in the 2.1 branch of the driver). | |
| 64 | + | |
| 65 | +You can use named setters even if the query uses anonymous parameters; | |
| 66 | +Cassandra will name the parameters after the column they apply to: | |
| 67 | + | |
| 68 | +```java | |
| 69 | +BoundStatement bound = ps1.bind() | |
| 70 | + .setString("sku", "324378") | |
| 71 | + .setString("description", "LCD screen"); | |
| 72 | +``` | |
| 73 | + | |
| 74 | +This can be ambiguous if the query uses the same column multiple times, | |
| 75 | +for example: `select * from sales where sku = ? and date > ? and date < | |
| 76 | +?`. In these situations, use positional setters or named parameters. | |
| 77 | + | |
| 78 | +A bound statement also has getters to retrieve the values. Note that | |
| 79 | +this has a small performance overhead since values are stored in their | |
| 80 | +serialized form. | |
| 81 | + | |
| 82 | +### How the driver handles prepared statements | |
| 83 | + | |
| 84 | +When the driver prepares a statement, it sends the query string to | |
| 85 | +Cassandra, which caches the statement and returns an identifier. Later, | |
| 86 | +when the driver needs to execute the statement, it just sends the | |
| 87 | +identifier and parameter values. Note that the identifier is | |
| 88 | +deterministic, so it will always be the same for all nodes (it's a | |
| 89 | +actually a hash of the query string). | |
| 90 | + | |
| 91 | +Prepared statements are not replicated across the cluster. It is the | |
| 92 | +driver's responsibility to ensure that each node's cache is up to | |
| 93 | +date. It uses a number of strategies to achieve this: | |
| 94 | + | |
| 95 | +1. When a statement is initially prepared, it is first sent to a single | |
| 96 | + node in the cluster (this prevents from hitting all nodes in case | |
| 97 | + the query string is wrong). Once that node replies successfully, the | |
| 98 | + driver re-prepares on all remaining nodes: | |
| 99 | + | |
| 100 | + ```ditaa | |
| 101 | + client driver node1 node2 node3 | |
| 102 | + --+------------------------+----------------+--------------+------+--- | |
| 103 | + | | | | | | |
| 104 | + | session.prepare(query) | | | | | |
| 105 | + |----------------------->| | | | | |
| 106 | + | | PREPARE(query) | | | | |
| 107 | + | |--------------->| | | | |
| 108 | + | | | | | | |
| 109 | + | | PREPARED(id) | | | | |
| 110 | + | |<---------------| | | | |
| 111 | + | | | | | | |
| 112 | + | | | | | | |
| 113 | + | | PREPARE(query) | | | |
| 114 | + | |------------------------------>| | | |
| 115 | + | | | | | | |
| 116 | + | | PREPARE(query) | | | |
| 117 | + | |------------------------------------->| | |
| 118 | + | | | | | | |
| 119 | + |<-----------------------| | | | | |
| 120 | + ``` | |
| 121 | + | |
| 122 | +2. if a node crashes, it loses all of its prepared statements. So the | |
| 123 | + driver keeps a client-side cache; anytime a node is marked back up, | |
| 124 | + the driver re-prepares all statements on it; | |
| 125 | + | |
| 126 | +3. finally, if the driver tries to execute a statement and finds out | |
| 127 | + that the coordinator doesn't know about it, it will re-prepare the | |
| 128 | + statement on the fly (this is transparent for the client, but will cost | |
| 129 | + two extra roundtrips): | |
| 130 | + | |
| 131 | + ```ditaa | |
| 132 | + client driver node1 | |
| 133 | + --+-------------------------------+------------------------------+-- | |
| 134 | + | | | | |
| 135 | + |session.execute(boundStatement)| | | |
| 136 | + +------------------------------>| | | |
| 137 | + | | EXECUTE(id, values) | | |
| 138 | + | |----------------------------->| | |
| 139 | + | | | | |
| 140 | + | | UNPREPARED | | |
| 141 | + | |<-----------------------------| | |
| 142 | + | | | | |
| 143 | + | | | | |
| 144 | + | | PREPARE(query) | | |
| 145 | + | |----------------------------->| | |
| 146 | + | | | | |
| 147 | + | | PREPARED(id) | | |
| 148 | + | |<-----------------------------| | |
| 149 | + | | | | |
| 150 | + | | | | |
| 151 | + | | EXECUTE(id, values) | | |
| 152 | + | |----------------------------->| | |
| 153 | + | | | | |
| 154 | + | | ROWS | | |
| 155 | + | |<-----------------------------| | |
| 156 | + | | | | |
| 157 | + |<------------------------------| | | |
| 158 | + ``` | |
| 159 | + | |
| 160 | +You can customize these strategies through `QueryOptions`: | |
| 161 | + | |
| 162 | +* [setPrepareOnAllHosts] controls whether statements are initially | |
| 163 | + re-prepared on other hosts (step 1 above); | |
| 164 | +* [setReprepareOnUp] controls whether statements are re-prepared on a | |
| 165 | + node that comes back up (step 2 above). | |
| 166 | + | |
| 167 | +Changing the driver's defaults should be done with care and only in | |
| 168 | +specific situations; read each method's Javadoc for detailed | |
| 169 | +explanations. | |
| 170 | + | |
| 171 | +[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean) | |
| 172 | +[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean) |
modified upgrade_guide/README.md +2 −2
| @@ -38,7 +38,7 @@ | ||
| 38 | 38 | ones. |
| 39 | 39 | |
| 40 | 40 | Also, note that the connection pool for protocol v3 can now be configured to |
| 41 | - use multiple connections. See [this page](../features/pooling) for more | |
| 41 | + use multiple connections. See [this page](../manual/pooling) for more | |
| 42 | 42 | information. |
| 43 | 43 | |
| 44 | 44 | 3. `MappingManager(Session)` will now force the initialization of the `Session` |
| @@ -207,7 +207,7 @@ | ||
| 207 | 207 | default like in previous versions. |
| 208 | 208 | |
| 209 | 209 | 3. Netty is not shaded anymore in the default Maven artifact. However we publish a |
| 210 | - [shaded artifact](../features/shaded_jar/) under a different classifier. | |
| 210 | + [shaded artifact](../manual/shaded_jar/) under a different classifier. | |
| 211 | 211 | |
| 212 | 212 | 4. The internal initialization sequence of the Cluster object has been slightly changed: |
| 213 | 213 | some fields that were previously initialized in the constructor are now set when |