`
sillycat
  • 浏览: 2543222 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

PHP Backend Application(6)Retry Function, PHPUNIT ENV and Async Redis and Large

 
阅读更多
PHP Backend Application(6)Retry Function, PHPUNIT ENV and Async Redis and Large File

1 Retry Functions in PHP
/**
* post json params to prediction
* @param string $path
* @param array $params, format will be ['key1' => 'value1', 'key2' => 'value2',]
* @return response
*/
public function post2Prediction($path, $params)
{
return $this->retry(function() use ($path, $params){

$response = $this->predictionClient->request('POST', $path, [


'json' => $params




]);


return $response;


}, 10, 3);

}


/**
* retry many times
* @param function $f
* @param number $delay
* @param number $retryies
*/
private function retry($f, $delay = 10, $retryies = 3){
$logger = $this->ioc->getService("logger");





try {

return $f();


}catch(Exception $e){

if($retryies > 0){


sleep($delay);



return retry($f, $delay, $retryies - 1);



}else{


$logger->error(\GuzzleHttp\Psr7\str($e->getRequest()));



if ($e->hasResponse()) {



$logger->error(\GuzzleHttp\Psr7\str($e->getResponse()));




}



}


}

}

2 phpunit Running Env
http://elnur.pro/using-environment-variables-to-add-flexibility-to-phpunit-tests/
Add the environment parameters in phpunit.xml, it works in Eclipse env
<phpunit bootstrap="tests/bootstrap_test.php">
<php>
<env name="RUNNING_ENV" value="test"/>

    </php>
  <testsuites>
    <testsuite name="unitsuite">
      <directory>tests</directory>
    </testsuite>
  </testsuites>

</phpunit>

In the command line,
RUNNING_ENV=test phpunit --bootstrap vendor/autoload.php tests/JobProducerPHP/JobsXMLParserTest

RUNNING_ENV=test php src/SuperStarProducer.php 12001 '/Users/carl/company/code/jobs-producer/data/12001.xml'

3 Object Inheritance in PHP
http://stackoverflow.com/questions/11237511/multiple-ways-of-calling-parent-method-in-php
http://php.net/manual/en/language.oop5.inheritance.php

Abstract Base class
<?php

namespace JobProducerPHP;

require __DIR__.'/../../vendor/autoload.php';

abstract class Import
{
     protected $ioc = null;



     public function __construct($ioc)

     {

          $this->ioc = $ioc;




          $logger = $this->ioc->getService("logger");


          $config = $this->ioc->getService("config");



     }

     public function printInfo(){


          $logger = $this->ioc->getService("logger");





          $logger->debug("calling method in parent class.");

     }


     public function printInfo2(){


          $logger = $this->ioc->getService("logger");





          $logger->debug("calling method2 in parent class.");

     }
}
?>

Sub Class had the actually implementation
<?php

namespace JobProducerPHP;

require __DIR__.'/../../vendor/autoload.php';

class ImportIndeedFmt extends Import
{

     public function printInfo2(){


          $logger = $this->ioc->getService("logger");





          $logger->debug("before calling parent");


          $this->printInfo();

          parent::printInfo2();


          $logger->debug("after calling parent");

     }
}

4 Predis-Async
https://github.com/nrk/predis-async/blob/master/examples/execute_commands.php

dependency
"predis/predis-async": "dev-master"


Async RedisClient, it works pretty well
<?php
namespace JobProducerPHP;

require __DIR__.'/../../vendor/autoload.php';

use \Predis\Async\Client;

class RedisClient
{

     private $client = null;

     private $ioc = null;

     public function __construct($ioc)
    {
$this->ioc = $ioc;


$logger = $this->ioc->getService("logger");

$config = $this->ioc->getService("config");





$logger->info("==============Redis config start ==============");

$logger->info("redisHost = " . $config['redisHost']);

$logger->info("redisPort = " . $config['redisPort']);

$logger->info("===============================================");


try

        {
    $this->client = new Client('tcp://' . $config['redisHost'] . ":" . $config['redisPort']);

    $logger->debug("Successfully set up Redis");

}

        catch (Exception $e)
        {
    $logger->error("Couldn't connected to Redis");

    $logger->error($e->getMessage());

}

}

/**
*
* @param array $messages format eg: array("key"=>"value", ...)
*/
public function setMessageBatch($messages)
{
$client = $this->client;

$logger = $this->ioc->getService("logger");

$queueClient = $this->ioc->getService("queueClient");





//send to redis

foreach($messages as $key => $value){

$client->connect(function ($client) use ($key, $value, $logger){


$logger->debug("connect to Redis success. 001");



$logger->debug("sending message for {$key} => {$value} 002");



$client->set($key, $value, function($response, $client) use ($logger, $key){



$logger->debug("response from server " . $response . " 003");




$client->disconnect();




});



});


$client->getEventLoop()->run();


$logger->debug("main thread runs here 004");


}

$logger->debug("main thread runs here 005");





//send to SQS

$keys = array_keys($messages);

$queueClient->sendMessageBatch($keys);

}

}

?>

5 PHP handle Large File
public function regexMatch($line){
return preg_match('</job>', $line);

}

public function splitLargeFile($filePath, $sourceID)
{
try{

$outputSize = 0;


$fileCount = 0;


$outputFile = null;


foreach( new SplFileObject('/data/1052.xml') as $line){


if($outputSize === 0){



$outputFileName = "/data/1052_split/{$fileCount}.xml";




$outputFile = fopen($outputFileName, "w");




}



$outputSize += strlen($line);



fwrite($outputFile, $line . PHP_EOL);



if($this->regexMatch($line) && $outputSize >= 100000000){



fclose($outputFile);




$outputSize = 0;




$fileCount++;




}



}


if($outputSize > 0){


fclose($outputFile);



}


}catch (Exception $e){

echo $e->getMessage();


}

}

PHP RegexUtil
public function regexMatchJob($line){
return preg_match('/<\/job>/i', $line);

}


public function extractReferenceNumber($line){
$result = '';

preg_match('/<[Rr]eferencenumber>(.*?)<\/[Rr]eferencenumber>/i', $line, $matches);

if(!empty($matches) && count($matches) > 1){

$result = $matches[1];


$result = preg_replace('/\]\]>/i','', $result);


$result = preg_replace('/<!\[CDATA\[/i','', $result);


}

return $result;

}


References:
retry system
https://gist.github.com/mudge/5948769

SOLR join
http://stackoverflow.com/questions/12665797/is-solr-4-0-capable-of-using-join-for-multiple-core

PRedis
https://github.com/phpredis/phpredis

Redis
http://redis.io/commands#sorted_set
分享到:
评论

相关推荐

    Building Scalable Apps with Redis and Node.js(PACKT,2014)

    You start with developing a backend web application followed by a frontend interface, and later on deploy it to the cloud platform. This book takes a holistic approach to server-side programming ...

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together epub

    Full-Stack Vue.js 2 and Laravel 5 Bring the frontend and backend together with Vue, Vuex, and Laravel 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网...

    Linux源码安装MySQL+MySQL主从+Nginx+Nginx负载均衡+redis+php+phpredis+tomcat

    在本教程中,我们将深入探讨如何在Linux环境中源码安装MySQL、MySQL主从复制、Nginx、Nginx负载均衡、Redis、PHP、phpredis以及Tomcat。这些技术是构建高效、可扩展的Web应用架构的基础。让我们逐一了解安装过程。 ...

    django-redis组件

    'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/0', # 替换为实际 Redis 服务器地址 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PASSWORD': '...

    ZendFramework 1 cache for Redis,Memcached

    $redisValue = $redisBackend-&gt;load('key'); $memcachedValue = $memcachedBackend-&gt;load('key'); ``` **文件名解析** 在提供的文件名列表中,我们有两个文件:`Memcached.php` 和 `Redis.php`。这些文件很可能...

    redis的session共享

    【Redis的Session共享】 在现代Web应用开发中,随着用户量的增长,服务器集群的使用变得越来越普遍。然而,用户Session的管理在分布式环境下成为一个挑战。为了解决这个问题,我们可以利用Redis这种高性能的键值...

    node-workflow-redis-backend:基于 Redis 构建的工作流后端

    npm install wf-redis-backend 用法 使用 wf 将以下内容添加到应用程序的配置文件中: { "backend": { "module": "wf-redis-backend", "opts": { "port": 6379, "host": "127.0.0.1", "db": 15 } } } 其中...

    Mastering The Faster Web with PHP, MySQL, and JavaScript 1st pdf

    Ensure seamless implementation of a JavaScript & HTML 5 CSS based frontend and PHP based backend. Learn about problem identification, best strategies, and UI design patterns as well to build a clean, ...

    店铺评价系统后端,redis 实战练习-comment-backend.zip

    在这个实战练习 "comment-backend" 中,我们可以深入学习如何利用 Redis 来优化店铺评价系统的后端性能。 首先,Redis 作为缓存可以显著提升数据读取速度。在评价系统中,可能会有大量用户同时查看热门店铺的评价,...

    利用redis实现session共享

    在`pom.xml`中添加依赖,然后配置`application.properties`,指定Redis服务器地址、端口和密钥前缀。 ```properties spring.session.store-type=redis spring.redis.host=localhost spring.redis.port=6379 spring....

    Backend_Application

    在项目"Backend_Application-main"中,我们可以期待找到与上述知识点相关的源代码、配置文件和资源。通过阅读和分析这些内容,可以深入理解一个基于Java的后端应用是如何设计和实现的。开发者可能还使用了Maven或...

    Tomcat7+Redis+Session 负载之后session 共享 tomcat jar包

    标题 "Tomcat7+Redis+Session 负载之后session 共享 tomcat jar包" 涉及的是在使用Nginx做负载均衡时,如何通过集成Redis来实现Tomcat7服务器之间的Session共享,从而确保用户在不同服务器之间切换时仍然能够保持...

    Python-django的celery和redis简单示例项目

    【Python-django的celery和redis简单示例项目】是一个基于Django框架的Web应用程序,它集成并展示了Celery和Redis这两个重要组件的使用。在这个项目中,Celery作为一个分布式任务队列,用于异步处理任务,而Redis则...

    ssm+redis+nginx实现session共享和负载均衡

    SSM(Spring、Spring MVC、MyBatis)是Java后端开发的常用框架组合,而Redis是一个高性能的键值数据库,常用于缓存和session存储。Nginx则是一款强大的反向代理服务器,能够实现负载均衡。接下来我们将深入探讨如何...

    Node.js Design Patterns Second Edition[July 2016]

    explores one of the most interesting capabilities of modern JavaScript web applications: being able to share application code between the frontend and the backend. Across this chapter we learn the ...

    python3开发django项目安装和使用redis教程

    'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } ``` ##### 4.2 配置 Redis 作为会话存储...

    statsd-redis-backend:跷跷板

    《statsd-redis-backend:构建高效数据收集与分析系统》 在现代的互联网应用开发中,数据监控和分析是至关重要的。"statsd-redis-backend"是一个针对此需求的解决方案,它结合了StatsD和Redis的强大功能,为开发者...

    NGINX + TOMCAT 6 + REDIS 实现负载均衡 session会话同步

    本篇文章将详细探讨如何使用NGINX作为负载均衡器,结合TOMCAT 6应用服务器和REDIS作为session会话存储来实现负载均衡下的session会话同步。 首先,我们需要理解负载均衡的基本概念。负载均衡是指在多台服务器之间...

    nginx-tomcat-redis负载均衡,session共享依赖jar包

    本文将详细介绍如何使用`nginx`、`Tomcat`和`Redis`来实现负载均衡和跨服务器的session共享,以及在这个过程中可能涉及的依赖jar包。 首先,`nginx`是一个高性能的反向代理服务器和负载均衡器,它可以通过将来自...

    PyPI 官网下载 | django-redis-sentinel-plugin-1.0.0.tar.gz

    'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://sentinel:26379/0', 'OPTIONS': { 'SENTINEL_KWARGS': {'hosts': {'sentinel1': ('localhost', 26379), 'sentinel2': ('localhost', 26380)}...

Global site tag (gtag.js) - Google Analytics