1.Cassandra驱动选择
   maven依赖配置pom.xml

<dependency>
    <groupId>com.datastax.cassandra</groupId>
    <artifactId>cassandra-driver-core</artifactId>
    <version>3.1.2</version>
</dependency>

2.单节点连接和集群连接代码

package weixuan.space.cassnadra;

import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;

import java.net.InetSocketAddress;

/**
 * Created by geweixuan on 2018/12/5.
 */
public class ConnectTest {

    /**
     * 指定连接node
     */
    public static void connectToNode() {
        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).build();
        //获取并输出相关的集群信息
        Metadata metadata = cluster.getMetadata();
        //getAllHosts() 获取所有节点连接的信息
        for (Host host : metadata.getAllHosts()) {
            System.out.println("------" + host.getAddress());
        }
        //Metadata原数据对象 输出键空间
        for (KeyspaceMetadata keyspaceMetadata : metadata.getKeyspaces()) {
            System.out.println("--------" + keyspaceMetadata.getName());
        }
        //关闭进程
        cluster.close();
        System.out.println("connectToNode go to end");
    }

    /**
     * 连接至集群
     * Cluster 四种Retry重试策略:(对数据库的操作失败后的重试)
     * 1.DefaultRetryPolicy 没有查询到数据,或者写入时超时的情况下进行重新查询
     * 2.DowngradingConsistencyRetryPolicy 与DefaultRetryPolicy一样,不同点是考虑了最终数据一致性问题
     * 3.FallthroughRetryPolicy 这一策略不重试查询,但允许客户端业务逻辑实现重试
     * 4.LoggingRetryPolicy 不重试查询,用来记录日志信息,info级别
     *
     * Cluster 两种节点重连策略:(节点连接不上重新连接)
     * 1.ConstantReconnectionPolicy 固定时间间隔进行重连
     * 2.ExponentialReconnectionPolicy 指数级别增加重连时间,但不会超过最大重连时间
     */
    public static void connectToCluster() {
        Cluster cluster = Cluster.builder()
                .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 9042))
                .addContactPointsWithPorts(new InetSocketAddress("127.0.0.2", 9042))
                .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
                .withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
                .build();
        cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.LZ4);
        cluster.close();
        System.out.println("connectToCluster go to end");
    }

    public static void main(String[] args) {
        connectToNode();
        connectToCluster();
    }
}

通过获取到的cluster即可获取session,然后进行相关的数据库操作。

转载于:https://blog.csdn.net/qq_23966225/article/details/84812663