Exemplo n.º 1
0
 private function requeueOldWorkingTasks()
 {
     $taskIds = array_unique($this->redis->lRange($this->getTaskRunKey(), 0, -1));
     foreach ($taskIds as $taskId) {
         $time = $this->redis->hGet($this->getTaskStartTimeKey(), $taskId);
         if (!empty($time) && time() > $this->taskTimeout + (int) $time) {
             $this->redis->multi();
             $this->redis->rPush($this->getTaskQueueKey(), $taskId);
             $this->redis->lRem($this->getTaskRunKey(), $taskId, 1);
             $this->redis->hDel($this->getTaskStartTimeKey(), $taskId);
         }
     }
 }
Exemplo n.º 2
0
 /**
  * Append a value to a list
  *
  * @param string $key
  * @param string $value
  * @throws CM_Exception_Invalid
  */
 public function rPush($key, $value)
 {
     $length = $this->_redis->rPush($key, $value);
     if (false === $length) {
         throw new CM_Exception_Invalid('Cannot push to list `' . $key . '`.');
     }
 }
 /**
  * Saves data in the cache.
  *
  * @param string $entryIdentifier An identifier for this specific cache entry
  * @param string $data The data to be stored
  * @param array $tags Tags to associate with this cache entry. If the backend does not support tags, this option can be ignored.
  * @param integer $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
  * @throws \RuntimeException
  * @return void
  * @api
  */
 public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
 {
     if ($this->isFrozen()) {
         throw new \RuntimeException(sprintf('Cannot add or modify cache entry because the backend of cache "%s" is frozen.', $this->cacheIdentifier), 1323344192);
     }
     if ($lifetime === null) {
         $lifetime = $this->defaultLifetime;
     }
     $setOptions = [];
     if ($lifetime > 0) {
         $setOptions['ex'] = $lifetime;
     }
     $this->redis->multi();
     $result = $this->redis->set($this->buildKey('entry:' . $entryIdentifier), $this->compress($data), $setOptions);
     if (!$result instanceof \Redis) {
         $this->verifyRedisVersionIsSupported();
     }
     $this->redis->lRem($this->buildKey('entries'), $entryIdentifier, 0);
     $this->redis->rPush($this->buildKey('entries'), $entryIdentifier);
     foreach ($tags as $tag) {
         $this->redis->sAdd($this->buildKey('tag:' . $tag), $entryIdentifier);
         $this->redis->sAdd($this->buildKey('tags:' . $entryIdentifier), $tag);
     }
     $this->redis->exec();
 }
Exemplo n.º 4
0
 /**
  * Add message to queue
  *
  * @param MessageInterface $message
  *
  * @return bool
  *
  * @throws \RuntimeException
  */
 public function addMessage(MessageInterface $message)
 {
     if (!$this->listKey) {
         throw new \RuntimeException('Can\'t send message. Undefined list key.');
     }
     if (null === $this->redis) {
         throw new \RuntimeException('Can\'t send message. Not found redis instance.');
     }
     return $this->redis->rPush($this->listKey, serialize($message));
 }
Exemplo n.º 5
0
 private function requeueOldWorkingMessages($type)
 {
     $messageIds = array_unique($this->redis->lRange($this->getMessageRunKey($type), 0, -1));
     foreach ($messageIds as $messageId) {
         $time = $this->redis->hGet($this->getMessageStartTimeKey($type), $messageId);
         if (!empty($time) && time() > $this->messageTimeout + (int) $time) {
             $this->redis->multi();
             $this->redis->rPush($this->getMessageQueueKey($type), $messageId);
             $this->redis->lRem($this->getMessageRunKey($type), $messageId, 1);
             $this->redis->hDel($this->getMessageStartTimeKey($type), $messageId);
             $this->redis->exec();
         }
     }
 }
Exemplo n.º 6
0
 public function testlGet()
 {
     $this->redis->delete('list');
     $this->redis->lPush('list', 'val');
     $this->redis->lPush('list', 'val2');
     $this->redis->lPush('list', 'val3');
     $this->assertEquals('val3', $this->redis->lGet('list', 0));
     $this->assertEquals('val2', $this->redis->lGet('list', 1));
     $this->assertEquals('val', $this->redis->lGet('list', 2));
     $this->assertEquals('val', $this->redis->lGet('list', -1));
     $this->assertEquals('val2', $this->redis->lGet('list', -2));
     $this->assertEquals('val3', $this->redis->lGet('list', -3));
     $this->assertEquals(FALSE, $this->redis->lGet('list', -4));
     $this->redis->rPush('list', 'val4');
     $this->assertEquals('val4', $this->redis->lGet('list', 3));
     $this->assertEquals('val4', $this->redis->lGet('list', -1));
 }
 /**
  * Saves data in the cache.
  *
  * @param string $entryIdentifier An identifier for this specific cache entry
  * @param string $data The data to be stored
  * @param array $tags Tags to associate with this cache entry. If the backend does not support tags, this option can be ignored.
  * @param integer $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
  * @throws \RuntimeException
  * @return void
  * @api
  */
 public function set($entryIdentifier, $data, array $tags = array(), $lifetime = NULL)
 {
     if ($this->isFrozen()) {
         throw new \RuntimeException(sprintf('Cannot add or modify cache entry because the backend of cache "%s" is frozen.', $this->cacheIdentifier), 1323344192);
     }
     if ($lifetime === NULL) {
         $lifetime = $this->defaultLifetime;
     }
     $setOptions = array();
     if ($lifetime > 0) {
         $setOptions['ex'] = $lifetime;
     }
     $this->redis->multi();
     $this->redis->set($this->buildKey('entry:' . $entryIdentifier), $data, $setOptions);
     $this->redis->rPush($this->buildKey('entries'), $entryIdentifier);
     foreach ($tags as $tag) {
         $this->redis->sAdd($this->buildKey('tag:' . $tag), $entryIdentifier);
         $this->redis->sAdd($this->buildKey('tags:' . $entryIdentifier), $tag);
     }
     $this->redis->exec();
 }
Exemplo n.º 8
0
 /**
  * Write to redis
  *
  * @return mixed|void
  */
 public function write()
 {
     foreach ($this->formattedMessages() as $message) {
         $this->client->rPush($this->injectors['key'], $message);
     }
 }
Exemplo n.º 9
0
 public function reloadServer()
 {
     if (!$this->checkIfRunning()) {
         $settings = $this->__setupPubServer();
     } else {
         $settings = $this->__getSetSettings();
         $redis = new Redis();
         $redis->connect($settings['redis_host'], $settings['redis_port']);
         $redis->select($settings['redis_database']);
         $redis->rPush($settings['redis_namespace'] . ':command', 'reload');
     }
     if (!$this->checkIfRunning()) {
         return 'Setting saved, but something is wrong with the ZeroMQ server. Please check the diagnostics page for more information.';
     }
     return true;
 }
Exemplo n.º 10
0
 /**
  * rpush a raw value
  *
  * @param	string	$key	Cache ID
  * @param	string	$value	value
  * @return	mixed	New value on success or FALSE on failure
  */
 public function rpush($key, $value)
 {
     return $this->_redis->rPush($key, $value);
 }
Exemplo n.º 11
0
 /**
  * @param int $key
  * @param mixed $message
  * @return bool
  */
 public function send($key, $message)
 {
     $result = 0 < $this->client->rPush($key, $message);
     return $result;
 }
Exemplo n.º 12
0
 /**
  * 入队列
  * @param $list string 队列名
  * @param $value mixed 入队元素值
  * @param $deriction int 0:数据入队列头(左) 1:数据入队列尾(右) 默认为0
  * @param $repeat int 判断value是否存在  0:不判断存在 1:判断存在 如果value存在则不入队列
  */
 public static function listPush($list, $value, $direction = 0, $repeat = 0)
 {
     $redis = new \Redis();
     $redis->connect(self::_HOST, self::_PORT);
     $return = null;
     switch ($direction) {
         case 0:
             if ($repeat) {
                 $return = $redis->lPushx($list, $value);
             } else {
                 $return = $redis->lPush($list, $value);
             }
             break;
         case 1:
             if ($repeat) {
                 $return = $redis->rPushx($list, $value);
             } else {
                 $return = $redis->rPush($list, $value);
             }
             break;
         default:
             $return = false;
             break;
     }
     $redis->close();
     $redis = null;
     return $return;
 }
Exemplo n.º 13
0
 private function checkSerializer($mode)
 {
     $this->redis->delete('key');
     $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === Redis::SERIALIZER_NONE);
     // default
     $this->assertTrue($this->redis->setOption(Redis::OPT_SERIALIZER, $mode) === TRUE);
     // set ok
     $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === $mode);
     // get ok
     // lPush, rPush
     $a = array('hello world', 42, TRUE, array('<tag>' => 1729));
     $this->redis->delete('key');
     $this->redis->lPush('key', $a[0]);
     $this->redis->rPush('key', $a[1]);
     $this->redis->rPush('key', $a[2]);
     $this->redis->rPush('key', $a[3]);
     // lGetRange
     $this->assertTrue($a === $this->redis->lGetRange('key', 0, -1));
     // lGet
     $this->assertTrue($a[0] === $this->redis->lGet('key', 0));
     $this->assertTrue($a[1] === $this->redis->lGet('key', 1));
     $this->assertTrue($a[2] === $this->redis->lGet('key', 2));
     $this->assertTrue($a[3] === $this->redis->lGet('key', 3));
     // lRemove
     $this->assertTrue($this->redis->lRemove('key', $a[3]) === 1);
     $this->assertTrue(array_slice($a, 0, 3) === $this->redis->lGetRange('key', 0, -1));
     // lSet
     $a[0] = array('k' => 'v');
     // update
     $this->assertTrue(TRUE === $this->redis->lSet('key', 0, $a[0]));
     $this->assertTrue($a[0] === $this->redis->lGet('key', 0));
     // lInsert
     $this->assertTrue($this->redis->lInsert('key', Redis::BEFORE, $a[0], array(1, 2, 3)) === 4);
     $this->assertTrue($this->redis->lInsert('key', Redis::AFTER, $a[0], array(4, 5, 6)) === 5);
     $a = array(array(1, 2, 3), $a[0], array(4, 5, 6), $a[1], $a[2]);
     $this->assertTrue($a === $this->redis->lGetRange('key', 0, -1));
     // sAdd
     $this->redis->delete('key');
     $s = array(1, 'a', array(1, 2, 3), array('k' => 'v'));
     $this->assertTrue(1 === $this->redis->sAdd('key', $s[0]));
     $this->assertTrue(1 === $this->redis->sAdd('key', $s[1]));
     $this->assertTrue(1 === $this->redis->sAdd('key', $s[2]));
     $this->assertTrue(1 === $this->redis->sAdd('key', $s[3]));
     // variadic sAdd
     $this->redis->delete('k');
     $this->assertTrue(3 === $this->redis->sAdd('k', 'a', 'b', 'c'));
     $this->assertTrue(1 === $this->redis->sAdd('k', 'a', 'b', 'c', 'd'));
     // sRemove
     $this->assertTrue(1 === $this->redis->sRemove('key', $s[3]));
     $this->assertTrue(0 === $this->redis->sRemove('key', $s[3]));
     // variadic
     $this->redis->delete('k');
     $this->redis->sAdd('k', 'a', 'b', 'c', 'd');
     $this->assertTrue(2 === $this->redis->sRem('k', 'a', 'd'));
     $this->assertTrue(2 === $this->redis->sRem('k', 'b', 'c', 'e'));
     $this->assertTrue(FALSE === $this->redis->exists('k'));
     // sContains
     $this->assertTrue(TRUE === $this->redis->sContains('key', $s[0]));
     $this->assertTrue(TRUE === $this->redis->sContains('key', $s[1]));
     $this->assertTrue(TRUE === $this->redis->sContains('key', $s[2]));
     $this->assertTrue(FALSE === $this->redis->sContains('key', $s[3]));
     unset($s[3]);
     // sMove
     $this->redis->delete('tmp');
     $this->redis->sMove('key', 'tmp', $s[0]);
     $this->assertTrue(FALSE === $this->redis->sContains('key', $s[0]));
     $this->assertTrue(TRUE === $this->redis->sContains('tmp', $s[0]));
     unset($s[0]);
     // sorted sets
     $z = array('z0', array('k' => 'v'), FALSE, NULL);
     $this->redis->delete('key');
     // zAdd
     $this->assertTrue(1 === $this->redis->zAdd('key', 0, $z[0]));
     $this->assertTrue(1 === $this->redis->zAdd('key', 1, $z[1]));
     $this->assertTrue(1 === $this->redis->zAdd('key', 2, $z[2]));
     $this->assertTrue(1 === $this->redis->zAdd('key', 3, $z[3]));
     // zDelete
     $this->assertTrue(1 === $this->redis->zDelete('key', $z[3]));
     $this->assertTrue(0 === $this->redis->zDelete('key', $z[3]));
     unset($z[3]);
     // check that zDelete doesn't crash with a missing parameter (GitHub issue #102):
     $this->assertTrue(FALSE === @$this->redis->zDelete('key'));
     // variadic
     $this->redis->delete('k');
     $this->redis->zAdd('k', 0, 'a');
     $this->redis->zAdd('k', 1, 'b');
     $this->redis->zAdd('k', 2, 'c');
     $this->assertTrue(2 === $this->redis->zDelete('k', 'a', 'c'));
     $this->assertTrue(1.0 === $this->redis->zScore('k', 'b'));
     $this->assertTrue($this->redis->zRange('k', 0, -1, true) == array('b' => 1.0));
     // zRange
     $this->assertTrue($z === $this->redis->zRange('key', 0, -1));
     // zScore
     $this->assertTrue(0.0 === $this->redis->zScore('key', $z[0]));
     $this->assertTrue(1.0 === $this->redis->zScore('key', $z[1]));
     $this->assertTrue(2.0 === $this->redis->zScore('key', $z[2]));
     // zRank
     $this->assertTrue(0 === $this->redis->zRank('key', $z[0]));
     $this->assertTrue(1 === $this->redis->zRank('key', $z[1]));
     $this->assertTrue(2 === $this->redis->zRank('key', $z[2]));
     // zRevRank
     $this->assertTrue(2 === $this->redis->zRevRank('key', $z[0]));
     $this->assertTrue(1 === $this->redis->zRevRank('key', $z[1]));
     $this->assertTrue(0 === $this->redis->zRevRank('key', $z[2]));
     // zIncrBy
     $this->assertTrue(3.0 === $this->redis->zIncrBy('key', 1.0, $z[2]));
     $this->assertTrue(3.0 === $this->redis->zScore('key', $z[2]));
     $this->assertTrue(5.0 === $this->redis->zIncrBy('key', 2.0, $z[2]));
     $this->assertTrue(5.0 === $this->redis->zScore('key', $z[2]));
     $this->assertTrue(2.0 === $this->redis->zIncrBy('key', -3.0, $z[2]));
     $this->assertTrue(2.0 === $this->redis->zScore('key', $z[2]));
     // mset
     $a = array('k0' => 1, 'k1' => 42, 'k2' => NULL, 'k3' => FALSE, 'k4' => array('a' => 'b'));
     $this->assertTrue(TRUE === $this->redis->mset($a));
     foreach ($a as $k => $v) {
         $this->assertTrue($this->redis->get($k) === $v);
     }
     $a = array('k0' => 1, 'k1' => 42, 'k2' => NULL, 'k3' => FALSE, 'k4' => array('a' => 'b'));
     // hSet
     $this->redis->delete('key');
     foreach ($a as $k => $v) {
         $this->assertTrue(1 === $this->redis->hSet('key', $k, $v));
     }
     // hGet
     foreach ($a as $k => $v) {
         $this->assertTrue($v === $this->redis->hGet('key', $k));
     }
     // hGetAll
     $this->assertTrue($a === $this->redis->hGetAll('key'));
     $this->assertTrue(TRUE === $this->redis->hExists('key', 'k0'));
     $this->assertTrue(TRUE === $this->redis->hExists('key', 'k1'));
     $this->assertTrue(TRUE === $this->redis->hExists('key', 'k2'));
     $this->assertTrue(TRUE === $this->redis->hExists('key', 'k3'));
     $this->assertTrue(TRUE === $this->redis->hExists('key', 'k4'));
     // hMSet
     $this->redis->delete('key');
     $this->redis->hMSet('key', $a);
     foreach ($a as $k => $v) {
         $this->assertTrue($v === $this->redis->hGet('key', $k));
     }
     // hMget
     $hmget = $this->redis->hMget('key', array_keys($a));
     foreach ($hmget as $k => $v) {
         $this->assertTrue($v === $a[$k]);
     }
     // getMultiple
     $this->redis->set('a', NULL);
     $this->redis->set('b', FALSE);
     $this->redis->set('c', 42);
     $this->redis->set('d', array('x' => 'y'));
     $this->assertTrue(array(NULL, FALSE, 42, array('x' => 'y')) === $this->redis->getMultiple(array('a', 'b', 'c', 'd')));
     // pipeline
     $this->sequence(Redis::PIPELINE);
     // multi-exec
     $this->sequence(Redis::MULTI);
     // keys
     $this->assertTrue(is_array($this->redis->keys('*')));
     // issue #62, hgetall
     $this->redis->del('hash1');
     $this->redis->hSet('hash1', 'data', 'test 1');
     $this->redis->hSet('hash1', 'session_id', 'test 2');
     $data = $this->redis->hGetAll('hash1');
     $this->assertTrue($data['data'] === 'test 1');
     $this->assertTrue($data['session_id'] === 'test 2');
     // issue #145, serializer with objects.
     $this->redis->set('x', array(new stdClass(), new stdClass()));
     $x = $this->redis->get('x');
     $this->assertTrue(is_array($x));
     $this->assertTrue(is_object($x[0]) && get_class($x[0]) === 'stdClass');
     $this->assertTrue(is_object($x[1]) && get_class($x[1]) === 'stdClass');
     // revert
     $this->assertTrue($this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE) === TRUE);
     // set ok
     $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === Redis::SERIALIZER_NONE);
     // get ok
 }
Exemplo n.º 14
0
 /**
  * @inheritdoc
  */
 public function push($data)
 {
     is_scalar($data) or $data = json_encode($data);
     return (bool) $this->redis->rPush($this->name, $data);
 }
Exemplo n.º 15
0
 /**
  * 数据入队列
  * @param string $key KEY名称
  * @param string|array $value 获取得到的数据
  * @param bool $right 是否从右边开始入
  * @return int
  */
 public function push($key, $value, $right = true)
 {
     $value = json_encode($value);
     return $right ? parent::rPush($key, $value) : parent::lPush($key, $value);
 }
Exemplo n.º 16
0
<?php

$objRedis = new Redis();
$objRedis->connect("localhost");
/* Pass straight through to motor command queue */
$objRedis->rPush('commandQueue', json_encode($_POST));
Exemplo n.º 17
0
 public function run()
 {
     $redis = new Redis();
     $redis->pconnect('127.0.0.1');
     echo "Run csvParser\n";
     $dbconn = pg_connect(DB_CONN_STR) or die('Не могу подключиться к БД: ' . pg_last_error());
     //Выберем все не занятые и включенные аккаунты с привязанным прокси
     $query = 'SELECT * FROM accounts WHERE status=0 AND busy<>1 AND proxy_ip<>0 ';
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $accounts = pg_fetch_all($result);
     if (count($accounts) < 1) {
         exit;
     }
     pg_free_result($result);
     //Берем рандомный из этого списка
     $acc_arr = array_rand($accounts);
     //Выбранный аккаунт становится занятым
     $query = 'UPDATE accounts SET busy=1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
     pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     //Выберем список работающих прокси
     $query = 'SELECT * FROM proxys WHERE id = ' . $accounts[$acc_arr]['proxy_ip'];
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $proxy_acc = pg_fetch_row($result);
     pg_free_result($result);
     //Берем случайный из списка
     $proxy = "{$proxy_acc[1]}:{$proxy_acc[2]}";
     $proxyauth = "{$proxy_acc[3]}:{$proxy_acc[4]}";
     //Получаем страну для которой запущен парсер
     $query = 'SELECT co."ID",co.full_name country, co.short_name cntr_code FROM countries co, params p ' . 'WHERE co."ID"=p.country_id';
     $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     $country = pg_fetch_object($result);
     pg_free_result($result);
     //Берем первый ключ в статусе "В ожидании" (keys_status = 1)
     //Если ключ в статусе "No Keywords" (keys_status = 2) - берем другой
     do {
         $key = $redis->sPop("keys_status:{$country->cntr_code}:1");
     } while ($redis->sIsMember("keys_status:{$country->cntr_code}:2", $key));
     //Увеличим количество использования аккаунта
     $query = 'UPDATE accounts SET cnt_work=cnt_work+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
     pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     echo "--email={$accounts[$acc_arr]['gm_login']} --pass={$accounts[$acc_arr]['gm_pass']} \n\n        --proxy={$proxy} --proxy-auth={$proxyauth} \n\n        --key={$key}";
     //Получаем время запуска и запускаем скрипт casperjs
     $start = microtime(true);
     $q = "/usr/local/bin/casperjs {$this->baseDir}googleKeyPlaner.js --proxy=" . $proxy . " --cookies-file={$this->baseDir}cookies/{$key}.txt " . "--proxy-auth=" . $proxyauth . " --ignore-ssl-errors=yes --web-security=no --key='{$key}' " . "--email={$accounts[$acc_arr]['gm_login']} --pass={$accounts[$acc_arr]['gm_pass']} " . "--verphone={$accounts[$acc_arr]['gm_tel']} --country='{$country->country}' > {$this->baseDir}tempFiles/{$key}-exitParser.txt";
     exec($q, $ret_arr, $ret_val);
     //Если casperjs вернул код выхода 100 - нет keywords для данного ключа. Блокируем ключ
     if ($ret_val == 100) {
         //Блокируем ключ со статусом "No keywords" (keys_status = 2)
         $redis->sAdd("keys_status:{$country->cntr_code}:2", $key);
         //Уменьшаем количество использования аккаунта
         $query = 'UPDATE accounts SET cnt_work=cnt_work-1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
         pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
         //Останавливаем процесс
         exit;
     }
     //Скачиваем файл по полученной ссылке для ключа
     if (is_file($this->baseDir . 'tempFiles/dnld_' . $key . '.txt')) {
         $dnldUrl = file($this->baseDir . 'tempFiles/dnld_' . $key . '.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
         echo '=================Start DownLoad=================';
         $q = "/usr/local/bin/casperjs {$this->baseDir}downloader.js --proxy=" . $proxy . " --cookies-file={$this->baseDir}cookies/{$key}.txt " . "--proxy-auth=" . $proxyauth . " --ignore-ssl-errors=yes --web-security=no --key='{$key}' " . "--dnldUrl='{$dnldUrl[0]}' > {$this->baseDir}tempFiles/{$key}-exitDownloader.txt";
         exec($q, $ret_arr, $ret_val);
     }
     $work_time = microtime(true) - $start;
     //Проверяем наличие скачанного файла для продолжения
     if (is_file($this->baseDir . 'tempGrab/stats_' . $key . '.csv')) {
         $csvObj = new File_CSV_DataSource();
         $csvObj->settings(array('delimiter' => "\t", 'eol' => ''));
         $csvObj->load($this->baseDir . 'tempGrab/stats_' . $key . '.csv');
         $csvObj->symmetrize(0);
         if (!$csvObj->isSymmetric()) {
             echo 'Ошибка! Количество заголовков и столбцов в строках не совпадает в файле tempGrab/stats_' . $key . '.csv';
         }
         //Если файл не пустой
         if ($csvObj->countRows() > 0) {
             $arrForSHA1 = array(0, 0);
             $mainKeyRow = $csvObj->getRow(0);
             //Добавляем информацию для заданного ключа
             $mainKey['keyword'] = $mainKeyRow[1] != "" ? $mainKeyRow[1] : "";
             $mainKey['AMS'] = $mainKeyRow[3] != "" ? $mainKeyRow[3] : 0;
             $mainKey['suggested_bid'] = $mainKeyRow[5] != "" ? $mainKeyRow[5] : 0;
             $redis->delete("key:{$country->cntr_code}:{$key}");
             $redis->hMset("key:{$country->cntr_code}:{$key}", $mainKey);
             $arrForSHA1[0] = sha1(serialize($mainKey));
             //Добавляем keywords для заданного ключа
             $new_words = array();
             $keywordRow = array();
             for ($i = 1; $i < $csvObj->countRows(); $i++) {
                 $childKeyRow = $csvObj->getRow($i);
                 $keywordRow[$i]['keyword'] = $childKeyRow[1] != "" ? $childKeyRow[1] : "";
                 $keywordRow[$i]['AMS'] = $childKeyRow[3] != "" ? $childKeyRow[3] : 0;
                 $keywordRow[$i]['suggested_bid'] = $childKeyRow[5] != "" ? $childKeyRow[5] : 0;
                 //Получаем новые слова для словоря
                 $new_words = array_merge($new_words, explode(" ", $keywordRow[$i]['keyword']));
             }
             //Если есть новые слова для словаря
             if (count($new_words)) {
                 //Удаляем дубликаты
                 $new_words = array_unique($new_words);
                 //Удаляем стоп-слова
                 $query = 'SELECT "stop_words" FROM countries ' . 'WHERE "ID"=' . $country->ID;
                 $result = pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
                 $st_words_str = pg_fetch_object($result)->stop_words;
                 pg_free_result($result);
                 if ($st_words_str) {
                     $st_words_arr = explode("\n", $st_words_str);
                     $new_words = array_diff($new_words, $st_words_arr);
                 }
                 //Если остались слова - продолжаем
                 if (count($new_words) > 0) {
                     //Удаляем однобуквенные слова и слова с запрещенными знаками
                     foreach ($new_words as $w_key => $value) {
                         if (!preg_match('|^[a-z]{2}[a-z0-9_-]*$|i', $value)) {
                             unset($new_words[$w_key]);
                             continue;
                         }
                     }
                     //Добавляем новые слова в словарь со статусом "В ожидании" (keys_status = 1)
                     if (count($new_words) > 0) {
                         $ins_arr = array();
                         foreach ($new_words as $word) {
                             if ($redis->exists("key:{$country->cntr_code}:{$word}") || $redis->sIsMember("keys_status:{$country->cntr_code}:2", $word)) {
                                 continue;
                             }
                             $redis->sAdd("keys_status:{$country->cntr_code}:1", strtolower(trim($word)));
                         }
                     }
                 }
             }
             //!!!! ПРОВЕРИТЬ КЛЮЧ В ХЭШ-ТАБЛИЦЕ !!!!!!!!!!!!!!!!!!!!
             //Добавляем keywords для ключа
             if (count($keywordRow) > 0) {
                 $arrForSHA1[1] = sha1(serialize($keywordRow));
                 $i = 1;
                 $redis->delete($redis->keys("keywords:{$country->cntr_code}:{$key}:*"));
                 foreach ($keywordRow as $row) {
                     $redis->hMset("keywords:{$country->cntr_code}:{$key}:{$i}", $row);
                     $i++;
                 }
             }
             $redis->delete("keys_hash:{$country->cntr_code}:{$key}");
             $redis->rPush("keys_hash:{$country->cntr_code}:{$key}", $arrForSHA1[0], $arrForSHA1[1]);
         } else {
             //Файл был пустой - разблокируем ключ (keys_status = 1)
             $redis->sAdd("keys_status:{$country->cntr_code}:1", $key);
             //Увеличиваем количество ошибок для аккаунта
             $query = 'UPDATE accounts SET cnt_fail=cnt_fail+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
             pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
         }
         //Удаляем скачанный файл
         if (is_file($this->baseDir . 'tempGrab/stats_' . $key . '.csv')) {
             unlink($this->baseDir . 'tempGrab/stats_' . $key . '.csv');
         }
     } else {
         //Файл не скачался - разблокируем ключ(keys_status = 1)
         $redis->sAdd("keys_status:{$country->cntr_code}:1", $key);
         //Увеличиваем количество ошибок для аккаунта
         $query = 'UPDATE accounts SET cnt_fail=cnt_fail+1 ' . "WHERE id={$accounts[$acc_arr]['id']}";
         pg_query($query) or die('Ошибка запроса: ' . pg_last_error());
     }
     sleep(1);
     pg_close($dbconn);
     echo "STOP Run csvParser\n";
 }
Exemplo n.º 18
0
    echo '<th width="4%">' . $ora . '</th>';
}
?>
</tr>

<?php 
for ($giorno = 1; $giorno <= 7; $giorno++) {
    echo "<tr>";
    echo '<td width="4%">' . $giorni[$giorno] . '</td>';
    for ($ora = 0; $ora <= 23; $ora++) {
        if ($ora == 0) {
            $redis->del($giorni[$giorno]);
        }
        echo "<td class=compatta>";
        //    echo $giorno."_".$ora;
        echo $_POST[$giorno . "_" . $ora];
        $redis->rPush($giorni[$giorno], $_POST[$giorno . "_" . $ora]);
        echo "</td>";
    }
    echo "</tr>";
}
?>
<tr><td colspan=25>
<a href=prog_settimana.php>Torna alla pagina di programmazione</a> - <a href=../>Torna alla home page</a>
</td></tr>
</table>
</form>
</div>
</body>
</html>
Exemplo n.º 19
0
 function push(Job $job)
 {
     $this->redis->rPush($this->key, serialize($job));
 }
Exemplo n.º 20
0
    if ($goodsCount > 0) {
        // 还存在商品,将用户放入一个数组中
        // 判断用户是否已经抢过了
        $exist = 0;
        $userArr = getUserList();
        foreach ($userArr as $key => $user) {
            if ($userArr[$key]['ip'] == $ip) {
                $exist = 1;
                break;
            }
        }
        if ($exist) {
            $arr['msg'] = $ip . '您已经抢到了商品,不能重复抢哦!';
        } else {
            $userInfo = array('ip' => $ip, 'addtime' => microtime());
            $redis->rPush('userlist', json_encode($userInfo));
            $redis->decr('goods_count');
            $arr['succ'] = 'T';
            $arr['msg'] = $userInfo['ip'] . '恭喜您,抢到了商品!';
        }
    } else {
        // 不存在商品了,直接返回数据
        $arr['msg'] = '商品已经抢光了,谢谢您的参与,下次再来吧';
    }
    backjson($arr);
} elseif ($act == 'user') {
    //获取中奖用户
    $msg = "";
    $userArr = getUserList();
    if (!empty($userArr)) {
        foreach ($userArr as $user) {
Exemplo n.º 21
0
 public function put($data, $options = null)
 {
     $this->redis->rPush($this->tube, $data);
 }
Exemplo n.º 22
0
        $data['field' . $j] = md5($j);
    }
    $redis->hMset('test:' . $incr . ':hset', $data);
}
// SET
for ($i = 0; $i <= rand(1000, 10000); $i++) {
    $incr = $redis->incr('test:incr:set');
    for ($j = 0; $j <= rand(10, 100); $j++) {
        $redis->sAdd('test:' . $incr . ':set', $j);
    }
}
// LIST
for ($i = 0; $i <= rand(1000, 10000); $i++) {
    $incr = $redis->incr('test:incr:list');
    for ($j = 0; $j <= rand(10, 100); $j++) {
        $redis->rPush('test:' . $incr . ':list', $j);
    }
}
// STRING
for ($i = 0; $i <= rand(1000, 10000); $i++) {
    $incr = $redis->incr('test:incr:string');
    for ($j = 0; $j <= rand(10, 100); $j++) {
        $redis->set('test:' . $incr . ':string', $j);
    }
}
// ZSET
for ($i = 0; $i <= rand(1000, 10000); $i++) {
    $incr = $redis->incr('test:incr:zset');
    for ($j = 0; $j <= rand(10, 100); $j++) {
        $redis->zAdd('test:' . $incr . ':zset', $j, md5($j));
    }
Exemplo n.º 23
0
<?php

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 加上时间戳存入队列
$now_time = date("Y-m-d H:i:s");
$interface_info = array('user_uuid' => '123456df', 'comment' => 'rwesdf');
$r_len = $redis->lLen("call_log");
//    for($i = 0; $i < $r_len; $i++){
//        $redis->lPop("call_log");
//    }
$interface_info = json_encode($interface_info);
for ($i = 1; $i <= 10000; $i++) {
    $redis->rPush("call_log", $interface_info);
}