NoSQL实现(3)——Cassandra - 掘金

  • 列族数据库

这一次使用的NoSQL数据库是Cassandra,它是一种列族数据库。与传通用数据库不同,列族数据库将数据存在列族中,一个列族中可以有多个列,一条记录可以有多个列族且用一个唯一的标识rowkey来表示。列族数据库的各行不一定要具备相同的列,可以在某一行中添加一个列而不把它加入其它行中。它与传统数据库的记录区别可以从以下两张图中看出来:

传统数据库,一行即为一个记录,每一条记录对应的列都相同

列族数据库,每一条记录可以有多个列族,且拥有的列可以不相同

  • Cassandra的配置

在Cassandra服务器的安装时,需要修改以下几个地方:

  1. data_file_directories:这是Cassandra数据存储的目录,可以将其修改到自己建立的data文件夹中。
  2. commitlog_directory :Cassandra提交日志文件夹,也可以将其修改。
  3. saved_caches_directory:Cassandra应保存计数器缓存,将缓存保存到设置的saved_caches_directory中

除此之外,因为在例子中写好了用户名和密码,因此需要将Cassandra服务器的验证方式修改为用户名+密码的验证方式,为此需要修改cassandra.yaml中的其它几个配置,让Cassandra使用用户名/密码验证:

  1.  authenticator :后端认证,用于标识用户,Cassandra提供了两种方法:AllowAllAuthenticator,PasswordAuthenticator。

    AllowAllAuthenticator:不执行任何检查 - 将其设置为禁用身份验证。 PasswordAuthenticator:依赖用户名/密码对来验证用户。如果使用了这个认证方式,那么还需要将role_manager设置为CassandraRoleManager。

     默认值为AllowAllAuthenticator,因为需要修改为用户名/密码验证所以将其修改为: 

    复制代码

    authenticator: org.apache.cassandra.auth.PasswordAuthenticator

  2. authorizer:后端授权,用于限制访问/提供权限,Cassandra提供了两种类型:AllowAllAuthorizer,CassandraAuthorizer。

    AllowAllAuthorizer:允许任何用户的任何操作。
    CassandraAuthorizer :通过授权决定登录之后用户具有哪些权限

    默认值为AllowAllAuthorizer,这里可以将其改成

    复制代码

    authorizer: org.apache.cassandra.auth.CassandraAuthorizer

  3. role_manager:部分认证和授权后端,用于维护角色之间的授权和成员资格。Cassandra只提供了CassandraRoleManager,它将角色信息存储在system_auth中。
  • 实例

  1. 先在application.properties里对连接Cassandra服务器进行配置:

    复制代码

    `#连接节点
    spring.data.cassandra.contact-points=127.0.0.1

    键值空间

    spring.data.cassandra.keyspace-name=test
    spring.data.cassandra.port=9042
    spring.data.cassandra.username=test
    spring.data.cassandra.password=test`

  2. 定义一个实体类,并加上@Table的注解,让其成为对应的表

    复制代码

    `@Table(value = "user")
    public class User implements Serializable {
    @PrimaryKey
    private String id;
    @Column(value = "name")
    private String name;
    @Column(value = "age")
    private int age;
    public User(String id,String name,int age){
    this.id = id;
    this.name = name;
    this.age = age;
    }
    ……
    }`

    与MongoDB不同,在标识主键的时候,Cassandra使用的注解是@PrimaryKey而不是@Id

  3. 编写一个UserRepository接口,让它继承CassandraRepository并自定义一个操作:

    复制代码

    `@Repository
    public interface UserRepository extends CassandraRepository<User,String> {
    User findUserById(String id);
    }`

  4. 编写一个Service,将UserRepository注入并运用其自带的一些操作完成增删改查的功能。

    复制代码

    `@Service
    public class UserService {
    @Autowired
    UserRepository repository;
    public void add(User u){
    repository.insert(u);
    System.out.println("INSERT SUCCESS");
    }
    ……
    }`


原网址: 访问
创建于: 2024-01-03 12:50:11
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论