Skip to content

Instantly share code, notes, and snippets.

@yeaha
Last active April 9, 2021 07:45
Show Gist options
  • Save yeaha/672178 to your computer and use it in GitHub Desktop.
Save yeaha/672178 to your computer and use it in GitHub Desktop.
Lysine存储服务水平/垂直切分机制样例
<?php
// 一个一致性hash实现 http://github.com/pda/flexihash
require '/path/to/flexihash/include/init.php';
require '/path/to/lysine/loader.php';
// user和topic数据垂直切分
// user数据放在mysql数据库
// topic数据放在postgresql数据库
// topic数据水平切分,分区到3台服务器上
$config = array(
'users' => array(
'class' => 'Lysine\Service\DB\Adapter\Mysql',
'dsn' => 'mysql:host=192.168.0.2 dbname=users',
'user' => 'dev',
'pass' => 'abc',
),
'topic1' => array(
'class' => 'Lysine\Service\DB\Adapter\Pgsql',
'dsn' => 'pgsql:host=192.168.0.3 dbname=topic',
'user' => 'dev',
'pass' => 'abc',
),
'topic2' => array(
'class' => 'Lysine\Service\DB\Adapter\Pgsql',
'dsn' => 'pgsql:host=192.168.0.4 dbname=topic',
'user' => 'dev',
'pass' => 'abc',
),
'topic3' => array(
'class' => 'Lysine\Service\DB\Adapter\Pgsql',
'dsn' => 'pgsql:host=192.168.0.5 dbname=topic',
'user' => 'dev',
'pass' => 'abc',
),
);
$topic_hash = new Flexihash();
foreach ($config as $node_name => $config) {
if (substr($node_name, 0, 5) == 'topic')
$topic_hash->addTarget($node_name);
}
$manager = Lysine\Service\Manager::getInstance();
$manager->importConfig($config);
// 名字叫topic的存储路由策略
// topic数据以id来分区
$manager->setDispatcher('topic', array($topic_hash, 'lookup'));
// 或者
$manager->setDispatcher('topic', function($topic_id) use ($topic_hash) {
return $topic_hash->lookup($topic_id);
});
// users数据库连接
$users_adapter = $manager->get('users');
// or
$users_adapter = service('users');
// id是100的topic数据库连接
$topic_adapter = $manager->get('topic', 100);
// or
$topic_adapter = service('topic', 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment