setReadPreference() public method

Set the read preference for this connection
public setReadPreference ( string $readPreference, array $tags = null ) : boolean
$readPreference string -
$tags array -
return boolean -
 /**
  * Connects to our database
  */
 public function connect()
 {
     // We don't need to throw useless exceptions here, the MongoDB PHP Driver has its own checks and error reporting
     // Yii will easily and effortlessly display the errors from the PHP driver, we should only catch its exceptions if
     // we wanna add our own custom messages on top which we don't, the errors are quite self explanatory
     if (version_compare(phpversion('mongo'), '1.3.0', '<')) {
         $this->_mongo = new Mongo($this->server, $this->options);
         $this->_mongo->connect();
         if ($this->setSlaveOkay) {
             $this->_mongo->setSlaveOkay($this->setSlaveOkay);
         }
     } else {
         $this->_mongo = new MongoClient($this->server, $this->options);
         if (is_array($this->RP)) {
             $const = $this->RP[0];
             $opts = $this->RP[1];
             if (!empty($opts)) {
                 // I do this due to a bug that exists in some PHP driver versions
                 $this->_mongo->setReadPreference(constant('MongoClient::' . $const), $opts);
             } else {
                 $this->_mongo->setReadPreference(constant('MongoClient::' . $const));
             }
         }
     }
 }
Example #2
0
 public static function factory($cfg)
 {
     if ($cfg instanceof Traversable) {
         $cfg = ArrayUtils::iteratorToArray($cfg);
     }
     if (!is_array($cfg)) {
         throw new \Exception('配置信息未设定');
     }
     if (!isset($cfg['cluster']) || empty($cfg['cluster'])) {
         throw new \Exception('配置信息中缺少cluster参数');
     }
     $options = array();
     //$options['connectTimeoutMS'] = 60000;
     //$options['socketTimeoutMS'] = 60000;
     //$options['w'] = 1;
     // $options['w'] = 3;
     //$options['wTimeout'] = 60000;
     if (isset($cfg['options']) && !empty($cfg['options'])) {
         $options = array_merge($options, $cfg['options']);
     }
     if (!isset($cfg['cluster']['default']) || empty($cfg['cluster']['default'])) {
         throw new \Exception('配置信息中缺少cluster.default参数');
     }
     $cluster = array();
     foreach ($cfg['cluster'] as $clusterName => $clusterInfo) {
         try {
             shuffle($clusterInfo['servers']);
             $dnsString = 'mongodb://' . join(',', $clusterInfo['servers']);
             if (class_exists('\\MongoClient')) {
                 $connect = new \MongoClient($dnsString, $options);
                 $connect->setReadPreference(\MongoClient::RP_PRIMARY_PREFERRED);
                 // 读取数据主优先
                 // $connect->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED);//读取数据从优先
                 $cluster[$clusterName]['connect'] = $connect;
             } else {
                 throw new \Exception('请安装PHP的Mongo1.4+版本的扩展');
             }
         } catch (\Exception $e) {
             if ($clusterName == 'default') {
                 throw new \Exception('无法与Mongodb建立连接' . $e->getMessage());
             } else {
                 break;
             }
         }
         try {
             if (is_array($clusterInfo['dbs']) && !empty($clusterInfo['dbs']) && $connect instanceof \MongoClient) {
                 foreach ($clusterInfo['dbs'] as $db) {
                     $cluster[$clusterName]['dbs'][$db] = $connect->selectDB($db);
                 }
             } else {
                 throw new \Exception('请设定cluster.name.dbs');
             }
         } catch (\Exception $e) {
             throw new \Exception('已经建立连接,但是无法访问指定的数据库');
         }
         unset($connect);
     }
     return new Config($cluster);
 }
Example #3
0
 /**
  * Wrapper method for MongoClient::setReadPreference().
  *
  * @see http://php.net/manual/en/mongoclient.setreadpreference.php
  * @param string $readPreference
  * @param array  $tags
  * @return boolean
  */
 public function setReadPreference($readPreference, array $tags = null)
 {
     $this->initialize();
     if (isset($tags)) {
         return $this->mongoClient->setReadPreference($readPreference, $tags);
     }
     return $this->mongoClient->setReadPreference($readPreference);
 }
Example #4
0
 protected function __property_client()
 {
     $options = $this->options + ['db' => $this->name];
     if ($this->username) {
         $options['username'] = $this->username;
     }
     if (false !== $this->password) {
         $options['password'] = $this->password;
     }
     if ($this->replicaSet) {
         $options['replicaSet'] = $this->replicaSet;
     }
     $options['connect'] = $this->connect;
     $options['connectTimeoutMS'] = $this->connectTimeoutMS;
     $options['socketTimeoutMS'] = $this->socketTimeoutMS;
     $options['secondaryAcceptableLatencyMS'] = $this->secondaryAcceptableLatencyMS;
     $host = str_replace(' ', '', implode(',', (array) $this->host));
     $client = new \MongoClient('mongodb://' . $host, $options, $this->socketContext ? ['context' => $this->socketContext] : []);
     $client->setReadPreference($this->readPreference, $this->readPreferenceTags);
     return $client;
 }
Example #5
0
/**
 *  @Service(activemongo, {
 *      host: {default: 'localhost'},
 *      user: {default: NULL},
 *      pass: {default: NULL},
 *      replicaSet: {default: NULL},
 *      db: {required: true},
 *      opts: { default:{}, type: 'hash'},
 *      path: { require: true, type: array_dir},
 *      temp_dir: { default: '/tmp', type: dir },
 *      w: {default: 1},
 *      devel: {default: true}
 *  }, { shared: true })
 */
function activemongo2_service($config)
{
    if (!$config['replicaSet']) {
        $conn = new \MongoClient($config['host'], $config['opts']);
    } else {
        $conn = new \MongoClient($config['host'], array("replicaSet" => $config['replicaSet']), $config['opts']);
        $conn->setReadPreference(\MongoClient::RP_SECONDARY);
        \MongoCursor::$slaveOkay = true;
    }
    $db = $conn->selectDB($config['db']);
    if ($config['user'] || $config['pass']) {
        $db->authenticate($config['user'], $config['pass']);
    }
    $conf = new \ActiveMongo2\Configuration($config['temp_dir'] . "/activemongo2__" . $db . ".php");
    foreach ((array) $config['path'] as $path) {
        $conf->addModelPath($path);
    }
    if ($config['devel']) {
        $conf->development();
    }
    $conf->setWriteConcern($config['w']);
    $mongo = new \ActiveMongo2\Connection($conf, $conn, $db);
    return $mongo;
}
Example #6
0
#!/usr/bin/php
<?php 
$document_id = '543f1ec50208373c53ba39b3';
// login and authenticate as read only user
$m = new MongoClient("mongodb://localhost:27200/statsdb");
// Prefer the nearest server with no tag preference
$m->setReadPreference(MongoClient::RP_NEAREST, array());
// get handle for statsdb and statistics collection
$db = $m->statsdb;
$statistics = $db->statistics;
$start_time = microtime(true);
// retrieve a record and display it
$statistical_record = $statistics->findOne(array("_id" => new MongoId($document_id)));
print "Found record with _id = {$statistical_record['_id']}.\n";
$stop_time = microtime(true);
// get the difference in seconds
$time_ms = ($stop_time - $start_time) * 1000;
print "Elapsed time from MongoDB was {$time_ms} seconds.\n\n";
// cache document
apc_store($document_id, $statistical_record);
$start_time = microtime(true);
// retrieve a record and display it
$statistical_record = apc_fetch($document_id);
print "Found record with _id = {$statistical_record['_id']}.\n";
$stop_time = microtime(true);
// get the difference in seconds
$time_ms = ($stop_time - $start_time) * 1000;
print "Elapsed time from cache was {$time_ms} seconds.\n\n";
Example #7
0
File: geo.php Project: im286er/ent
<?php

try {
    $options = array();
    $options['connectTimeoutMS'] = 60000;
    $options['socketTimeoutMS'] = 60000;
    $options['w'] = 1;
    $options['wTimeout'] = 60000;
    $connect = new \MongoClient("mongodb://10.0.0.31:57017", $options);
    $connect->setReadPreference(\MongoClient::RP_PRIMARY_PREFERRED);
    $db = $connect->selectDB('ICCv1');
    // $collection = new MongoCollection($db, 'idatabase_collection_5372fccc49961910538b4570');
    $collection = new MongoCollection($db, 'idatabase_collection_5372fccc49961910538b4570');
    $collection->ensureIndex(array('location' => '2d'));
    // $cursor = $collection->find(array(
    // '$and' => array(
    // 0 => array(
    // '__REMOVED__' => FALSE
    // ),
    // 1 => array(
    // '$and' => array(
    // 0 => array(
    // 'location' => array(
    // '$near' => array(
    // 0 => 123,
    // 1 => 123
    // ),
    // '$maxDistance' => 0.089992800575954
    // )
    // )
    // )