- 浏览: 2539168 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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
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
发表评论
-
Stop Update Here
2020-04-28 09:00 310I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 465NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 361Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 363Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 328Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 419Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 364Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 444VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 376Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 463NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 413Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 330Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 242GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 443GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 320GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 284Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 302Serverless with NodeJS and Tenc ...
相关推荐
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 with Vue, Vuex, and Laravel 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网...
在本教程中,我们将深入探讨如何在Linux环境中源码安装MySQL、MySQL主从复制、Nginx、Nginx负载均衡、Redis、PHP、phpredis以及Tomcat。这些技术是构建高效、可扩展的Web应用架构的基础。让我们逐一了解安装过程。 ...
'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/0', # 替换为实际 Redis 服务器地址 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PASSWORD': '...
$redisValue = $redisBackend->load('key'); $memcachedValue = $memcachedBackend->load('key'); ``` **文件名解析** 在提供的文件名列表中,我们有两个文件:`Memcached.php` 和 `Redis.php`。这些文件很可能...
【Redis的Session共享】 在现代Web应用开发中,随着用户量的增长,服务器集群的使用变得越来越普遍。然而,用户Session的管理在分布式环境下成为一个挑战。为了解决这个问题,我们可以利用Redis这种高性能的键值...
npm install wf-redis-backend 用法 使用 wf 将以下内容添加到应用程序的配置文件中: { "backend": { "module": "wf-redis-backend", "opts": { "port": 6379, "host": "127.0.0.1", "db": 15 } } } 其中...
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, ...
在这个实战练习 "comment-backend" 中,我们可以深入学习如何利用 Redis 来优化店铺评价系统的后端性能。 首先,Redis 作为缓存可以显著提升数据读取速度。在评价系统中,可能会有大量用户同时查看热门店铺的评价,...
在`pom.xml`中添加依赖,然后配置`application.properties`,指定Redis服务器地址、端口和密钥前缀。 ```properties spring.session.store-type=redis spring.redis.host=localhost spring.redis.port=6379 spring....
在项目"Backend_Application-main"中,我们可以期待找到与上述知识点相关的源代码、配置文件和资源。通过阅读和分析这些内容,可以深入理解一个基于Java的后端应用是如何设计和实现的。开发者可能还使用了Maven或...
标题 "Tomcat7+Redis+Session 负载之后session 共享 tomcat jar包" 涉及的是在使用Nginx做负载均衡时,如何通过集成Redis来实现Tomcat7服务器之间的Session共享,从而确保用户在不同服务器之间切换时仍然能够保持...
【Python-django的celery和redis简单示例项目】是一个基于Django框架的Web应用程序,它集成并展示了Celery和Redis这两个重要组件的使用。在这个项目中,Celery作为一个分布式任务队列,用于异步处理任务,而Redis则...
SSM(Spring、Spring MVC、MyBatis)是Java后端开发的常用框架组合,而Redis是一个高性能的键值数据库,常用于缓存和session存储。Nginx则是一款强大的反向代理服务器,能够实现负载均衡。接下来我们将深入探讨如何...
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 ...
'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的强大功能,为开发者...
本篇文章将详细探讨如何使用NGINX作为负载均衡器,结合TOMCAT 6应用服务器和REDIS作为session会话存储来实现负载均衡下的session会话同步。 首先,我们需要理解负载均衡的基本概念。负载均衡是指在多台服务器之间...
本文将详细介绍如何使用`nginx`、`Tomcat`和`Redis`来实现负载均衡和跨服务器的session共享,以及在这个过程中可能涉及的依赖jar包。 首先,`nginx`是一个高性能的反向代理服务器和负载均衡器,它可以通过将来自...
'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://sentinel:26379/0', 'OPTIONS': { 'SENTINEL_KWARGS': {'hosts': {'sentinel1': ('localhost', 26379), 'sentinel2': ('localhost', 26380)}...