hendrahuang/cassandra-bundle

Symfony2 / Symfony 3 的基于 datastax/php-driver 的 bundle

安装量: 3,322

依赖者: 0

建议者: 0

安全: 0

星标: 8

关注者: 6

分支: 26

类型:symfony-bundle

v1.8.0 2019-04-15 14:18 UTC

This package is auto-updated.

Last update: 2024-09-16 02:18:33 UTC


README

CassandraBundle 提供了一个 Cassandra EntityManager 作为 Symfony 服务。

安装

注意:您需要 安装官方的数据stax php 驱动扩展

安装 bundle

$ composer require hendrahuang/cassandra-bundle

在您的 kernel 中注册 bundle

// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        new CassandraBundle\CassandraBundle(),
    );
}

示例用法

在您的配置文件中添加 cassandra 部分。以下是所需的最小配置。

# app/config/config.yml

cassandra:
    connections:
        default:
            keyspace: "mykeyspace"
            hosts:
                - 127.0.0.1
                - 127.0.0.2
                - 127.0.0.3
            user: ''
            password: ''
# app/config/config_prod.yml

cassandra:
    dispatch_events: false

为 Cassandra 模式创建实体

<?php

namespace AppBundle\Entity;

use CassandraBundle\Cassandra\ORM\Mapping as ORM;

/**
 * @ORM\Table(
 *      repositoryClass = "AppBundle\Repository\HotelRepository",
 *      indexes = {"tags"},
 * )
 */
class Hotel
{
    /**
     * @ORM\Column(name="id", type="uuid")
     */
    private $id;

    /**
     * @ORM\Column(name="name", type="text")
     */
    private $name;

    /**
     * @ORM\Column(name="tags", type="set<text>")
     */
    private $tags;

    /**
     * @ORM\Column(name="config", type="map<text, frozen<map<text, text>>>")
     */
    private $config;

    // ...
}

运行控制台命令以创建 Cassandra 模式

$ bin/console cassandra:schema:create

注意:在运行命令之前,您需要手动在 Cassandra 中创建您的键空间

您可以创建用于自定义查询的存储库

<?php

namespace AppBundle\Repository;

use CassandraBundle\Cassandra\Utility\Type as CassandraType;

class HotelRepository extends \CassandraBundle\Cassandra\ORM\EntityRepository
{
    public function findByIds($ids = [])
    {
        $em = $this->getEntityManager();
        $cql = sprintf(
            'SELECT * FROM %s WHERE id IN (%s)', 
            $this->getTableName(),
            implode(', ', array_map(function () { return '?'; }, $ids))
        );
        $statement = $em->prepare($cql);
        $arguments = new \Cassandra\ExecutionOptions(['arguments' => array_map(function ($id) { return CassandraType::transformToCassandraType('uuid', $id); }, $ids)]);

        return $this->getResult($statement, $arguments);
    }
}

然后您可以使用 EntityManager 插入或查询数据

        $em = $this->get('cassandra.default_entity_manager');

        $hotel = new \AppBundle\Entity\Hotel();
        $hotel->setId('26fd2706-8baf-433b-82eb-8c7fada847da');
        $hotel->setName('name');
        $hotel->setTags(['wifi', 'AC']);
        $now = new \Datetime();
        $hotel->setConfig([
            'url' => [
                'slug' => 'new-hotel',
            ],
        ]);
        $em->insert($hotel); // Insert entity to cassandra

        $em->flush();

        $repository = $em->getRepository('AppBundle:Hotel');
        $hotels = $repository->findAll(); // Query all hotels
        $hotels = $repository->findByIds(['26fd2706-8baf-433b-82eb-8c7fada847da', '86fd2706-8baf-433b-82eb-8c7fada847da']); // Query hotels by $ids
        $hotel = $repository->find('26fd2706-8baf-433b-82eb-8c7fada847da'); // Query hotel by id
        $hotel->setName('new name');
        $em->update($hotel); // Update entity
        
        $em->flush();

Bundle 提供一个用于从时间uuid字符串中提取 Datetime 的实用类。

use CassandraBundle\Cassandra\Utility\Type as TypeUtils;

$datetime = TypeUtils::getDateTimeFromTimeuuidString('513a5340-6da0-11e5-815e-93ec150e89fd');

if (is_null($datetime)) {
    // something is wrong with supplied uuid
} else {
    echo $datetime->format(\DateTime::W3C); // 2015-10-08 11:38:22+02:00
}

数据收集器

当启用 symfony 分析器时,数据收集器可用。收集器允许您查看以下 Cassandra 数据

  • 键空间
  • 命令名称
  • 命令参数
  • 执行时间
  • 执行选项覆盖(一致性、序列一致性、页面大小和超时)

注意:由于使用了异步调用(executeAsyncprepareAsync),数据收集器中报告的时间可能不是实际的执行时间

EntityManager

EntityManager 与一个连接相关联,因此一个 Cassandra 键空间。在 bundle 中,您可以映射一些实体文件夹到一个 entityManager,然后创建一些表(通过 SchemaManager)到特定的键空间。在 orm 下有一个配置参数名为 entity_managers,您可以在其中描述每个 entity_manager。entityManager 配置包含关联的连接和实体映射目录。

如果找不到关联的连接,将回退到默认连接

配置参考

cassandra:
    dispatch_events: true                 # By default event are triggered on each cassandra command
    connections:
        default:
            persistent_sessions: true     # persistent session connection 
            keyspace: "mykeyspace"        # required keyspace to connect
            load_balancing: "round-robin" # round-robin or dc-aware-round-robin
            dc_options:                   # required if load balancing is set to dc-aware-round-robin
                local_dc_name: "testdc"
                host_per_remote_dc: 3
                remote_dc_for_local_consistency: false
            default_consistency: "one"    # 'one', 'any', 'two', 'three', 'quorum', 'all', 'local_quorum', 'each_quorum', 'serial', 'local_serial', 'local_one'
            default_pagesize: 10000       # -1 to disable pagination
            hosts:                        # required list of ip to contact
                - 127.0.0.1
            port: 9042                    # cassandra port
            token_aware_routing: true     # Enable or disable token aware routing
            user: ""                      # username for authentication
            password: ""                  # password for authentication
            ssl: false                    # set up ssl context
            default_timeout: null         # default is null, must be an integer if set
            timeout:
                connect: 5 
                request: 5 
            retries:
                sync_requests: 0          # Number of retries for synchronous requests. Default is 0, must be an integer if set

        client_name:
            ...
    orm:
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                mappings:
                    User:
                        dir: "src/UserEntity"
                    Preference:
                        dir: "src/PreferenceEntity"
            
            client_name:
                connection: client_name
                mappings:
                    EntityGroupOne:
                        dir: "src/GroupOneEntity"
            ...

运行测试

安装 composer 开发依赖

$ composer install --dev

然后使用 atoum 单元测试框架运行测试