Cassandra--Java API

  前面已经说了一种访问Cassandra的一种方式CQL,本篇博客还讲解一下其他的方式访问,主要是以Java API的方式,当然它是支持很多语言的,看看下图就知道了:

Java API

  • Cassandra 的Java API官网给出了如下几种,都是一些公司写的开源客户端,我们这里主要看一下datastax的
    Cassandra Java API

直接看代码吧

  • 访问前修改一下cassandra.yaml配置文件

    1
    2
    3
    start_rpc: true
    rpc_address: 0.0.0.0
    broadcast_rpc_address: 1.2.3.4
  • 下面的代码来源于:https://github.com/jbisso/cassandra-samples

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    import com.datastax.driver.core.Cluster;
    import com.datastax.driver.core.Metadata;
    import com.datastax.driver.core.ResultSet;
    import com.datastax.driver.core.Row;
    import com.datastax.driver.core.Session;

    /**
    * A simple client application that illustrates connecting to
    * a Cassandra cluster. retrieving metadata, creating a schema,
    * loading data into it, and then querying it.
    */
    public class SimpleClient {
    private Session session;

    public SimpleClient() {
    }

    /**
    * Connects to the specified node.
    * @param node a host name or IP address of the node in the cluster
    */
    public void connect(String node) {
    Cluster cluster = Cluster.builder()
    .addContactPoint(node)
    // .withCredentials("xiaoxiaomo", "blog")
    .build();
    Metadata metadata = cluster.getMetadata();
    System.out.printf("Connected to cluster: %s\n",
    metadata.getClusterName());
    session = cluster.connect();
    }


    public void connect(String[] nodes,int port) {
    Cluster cluster = Cluster.builder()
    .addContactPoints(nodes)
    .withPort(port)
    .withCredentials("xiaoxiaomo", "blog")
    .build();

    Metadata metadata = cluster.getMetadata();
    System.out.printf("Connected to cluster: %s\n",
    metadata.getClusterName());
    session = cluster.connect();
    }



    /**
    * Creates the simplex keyspace and two tables, songs and playlists.
    */
    public void createSchema() {
    session.execute(
    "CREATE KEYSPACE IF NOT EXISTS simplex WITH replication " +
    "= {'class':'SimpleStrategy', 'replication_factor':3};");
    // create songs and playlist tables
    session.execute(
    "CREATE TABLE IF NOT EXISTS simplex.songs (" +
    "id uuid PRIMARY KEY," +
    "title text," +
    "album text," +
    "artist text," +
    "tags set<text>," +
    "data blob" +
    ");");
    session.execute(
    "CREATE TABLE IF NOT EXISTS simplex.playlists (" +
    "id uuid," +
    "title text," +
    "album text, " +
    "artist text," +
    "song_id uuid," +
    "PRIMARY KEY (id, title, album, artist)" +
    ");");
    System.out.println("Simplex keyspace and schema created.");
    }

    /**
    * Loads some data into the schema so that we can query the tables.
    */
    public void loadData() {
    // insert data in the tables
    session.execute(
    "INSERT INTO simplex.songs (id, title, album, artist, tags) " +
    "VALUES (" +
    "756716f7-2e54-4715-9f00-91dcbea6cf50," +
    "'La Petite Tonkinoise'," +
    "'Bye Bye Blackbird'," +
    "'Joséphine Baker'," +
    "{'jazz', '2013'})" +
    ";");
    session.execute(
    "INSERT INTO simplex.songs (id, title, album, artist, tags) " +
    "VALUES (" +
    "f6071e72-48ec-4fcb-bf3e-379c8a696488," +
    "'Die Mösch'," +
    "'In Gold'," +
    "'Willi Ostermann'," +
    "{'kölsch', '1996', 'birds'}" +
    ");");
    session.execute(
    "INSERT INTO simplex.songs (id, title, album, artist, tags) " +
    "VALUES (" +
    "fbdf82ed-0063-4796-9c7c-a3d4f47b4b25," +
    "'Memo From Turner'," +
    "'Performance'," +
    "'Mick Jager'," +
    "{'soundtrack', '1991'}" +
    ");");
    session.execute(
    "INSERT INTO simplex.playlists (id, song_id, title, album, artist) " +
    "VALUES (" +
    "2cc9ccb7-6221-4ccb-8387-f22b6a1b354d," +
    "756716f7-2e54-4715-9f00-91dcbea6cf50," +
    "'La Petite Tonkinoise'," +
    "'Bye Bye Blackbird'," +
    "'Joséphine Baker'" +
    ");");
    session.execute(
    "INSERT INTO simplex.playlists (id, song_id, title, album, artist) " +
    "VALUES (" +
    "2cc9ccb7-6221-4ccb-8387-f22b6a1b354d," +
    "f6071e72-48ec-4fcb-bf3e-379c8a696488," +
    "'Die Mösch'," +
    "'In Gold'," +
    "'Willi Ostermann'" +
    ");");
    session.execute(
    "INSERT INTO simplex.playlists (id, song_id, title, album, artist) " +
    "VALUES (" +
    "3fd2bedf-a8c8-455a-a462-0cd3a4353c54," +
    "fbdf82ed-0063-4796-9c7c-a3d4f47b4b25," +
    "'Memo From Turner'," +
    "'Performance'," +
    "'Mick Jager'" +
    ");");
    System.out.println("Data loaded.");
    }

    /**
    * Queries the songs and playlists tables for data.
    */
    public void querySchema() {
    ResultSet results = session.execute(
    "SELECT * FROM simplex.playlists " +
    "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;");
    System.out.println(
    String.format("%-30s\t%-20s\t%-20s\n%s", "title", "album", "artist",
    "-------------+------------------+---------------"));
    for (Row row : results) {
    System.out.println(
    String.format("%-30s\t%-20s\t%-20s",
    row.getString("title"),
    row.getString("album"),
    row.getString("artist")));
    }
    System.out.println();
    }

    /**
    * Updates the songs table with a new song and then queries the table
    * to retrieve data.
    */
    public void updateSchema() {
    session.execute(
    "UPDATE simplex.songs " +
    "SET tags = tags + { 'entre-deux-guerres' } " +
    "WHERE id = 756716f7-2e54-4715-9f00-91dcbea6cf50;");

    ResultSet results = session.execute(
    "SELECT * FROM simplex.songs " +
    "WHERE id = 756716f7-2e54-4715-9f00-91dcbea6cf50;");

    System.out.println(
    String.format("%-30s\t%-20s\t%-20s%-30s\n%s",
    "title", "album", "artist", "tags",
    "--------------------------+-----------------+-----------------+-------"));

    for (Row row : results) {
    System.out.println(
    String.format("%-30s\t%-20s\t%-20s",
    row.getString("title"),
    row.getString("album"),
    row.getString("artist"),
    row.getSet("tags", String.class)));
    }
    }

    /**
    * Drops the specified schema.
    * @param keyspace the keyspace to drop (and all of its data)
    */
    public void dropSchema(String keyspace) {
    getSession().execute("DROP KEYSPACE " + keyspace);
    System.out.println("Finished dropping " + keyspace + " keyspace.");
    }

    /**
    * Returns the current session.
    * @return the current session to execute statements on
    */
    public Session getSession() {
    return this.session;
    }

    // used by the workaround method in the BoundStatementsclient child class.
    void setSession(Session session) {
    this.session = session;
    }

    /**
    * Shuts down the session and its cluster.
    */
    public void close() {
    session.close();
    session.getCluster().close();
    }

    /**
    * Creates simple client application that illustrates connecting to
    * a Cassandra cluster. retrieving metadata, creating a schema,
    * loading data into it, and then querying it.
    * @param args ignored
    */
    public static void main(String[] args) {
    SimpleClient client = new SimpleClient();
    client.connect("10.141.5.27");
    client.createSchema();
    client.loadData();
    client.querySchema();
    client.updateSchema();
    client.dropSchema("simplex");
    client.close();
    }
    }

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器