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

PHP Backend Application(5)Redis Advanced and PHP Memory and HTTP Client

 
阅读更多
PHP Backend Application(5)Redis Advanced and PHP Memory and HTTP Client

1 Trouble Shooting PHP Memory and TimeZone Issue
Error Message:
1) SegmentServiceTest::testGetCampaignConfig
date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.

Solution:
http://stackoverflow.com/questions/16765158/date-it-is-not-safe-to-rely-on-the-systems-timezone-settings

I met this issue when I install Symfony long time ago
http://sillycat.iteye.com/blog/2149513

> cat /etc/php.ini
; http://php.net/date.timezone
date.timezone = America/North_Dakota/Center
display_errors = On
memory_limit = 512M

Since I manually install the php myself, so my php.ini file actually is in this place.
> ls -l /etc/ | grep php
lrwxrwxrwx  1 root root      20 Jun 17 02:43 php.ini -> /opt/php/lib/php.ini

Memory Issues
> phpunit --bootstrap vendor/autoload.php tests/JobConsumerPHP/SegmentServiceTest
PHPUnit 5.4.6 by Sebastian Bergmann and contributors.

..
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 3248 bytes) in /home/ec2-user/users/carl/jobs-consumerphp/src/JobConsumerPHP/SegmentService.php on line 166

Solution:
give more memory limit in php.ini as follow:
memory_limit = 512M

2 HTTP Client
I plan to use this client library.
http://docs.guzzlephp.org/en/latest/request-options.html#json
https://github.com/guzzle/guzzle

Set up the configuration in composer.json
"guzzlehttp/guzzle": "^6.2"


Try to initiate the client in base class and reuse them.
<?php

namespace JobConsumerPHP;

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

use \GuzzleHttp\Client;
use \GuzzleHttp\Psr7\Request;

class WebHttpClient
{

    protected $classifierClient = null;

    protected $predictionClient = null;

    protected $ioc = null;

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

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

        $logger->info("==============WebClient config start ==============");
        $classifierURL = $config['classifierURL'];
        $classifierKey = $config['classifierKey'];

        $predictionURL = $config['predictionURL'];
        $predictionKey = $config['predictionKey'];

        $gatewayKey = $config['gatewayKey'];
        $httpTimeout = $config['httpTimeout'];

        $logger->info("classifierURL = {$classifierURL}");
        $logger->info("classifierKey = {$classifierKey}");
        $logger->info("predictionURL = {$predictionURL}");
        $logger->info("predictionKey = {$predictionKey}");
        $logger->info("predictionKey = {$predictionKey}");
        $logger->info("httpTimeout = {$httpTimeout}");
        $logger->info("=============================================");

        try
        {
            $this->classifierClient = new Client([
                'base_uri' => $classifierURL,
                'timeout' => $httpTimeout,
                'connect_timeout'=> $httpTimeout,
            ]);
            $this->predictionClient = new Client([
                    'base_uri' => $predictionURL,
                    'timeout' => $httpTimeout,
                    'connect_timeout' => $httpTimeout,
                    'headers' => [
                            'Content-Type' => 'application/json',
                            'x-api-key' => $predictionKey,
                            'api-gateway-key' => $gatewayKey,
                    ],
            ]);
        } catch (Exception $e) {
            $logger->error("Couldn't init the HTTP Client.");
            $logger->error($e->getMessage());
        }
    }

    /**
     * post params to classifier
     * @param string $path
     * @param array $params, format will be ['key1'=>'value1', 'key2'=>'value2',]
     * @return response
     */
    public function post2Classifier($path, $params)
    {
        $logger = $this->ioc->getService("logger");

        try{
            $response = $this->classifierClient->request('POST', $path, [
                    'form_params' => $params
                ]
            );
            return $response;
        }catch(RequestException $e){
            $logger->error(\GuzzleHttp\Psr7\str($e->getRequest()));
            if ($e->hasResponse()) {
                $logger->error(\GuzzleHttp\Psr7\str($e->getResponse()));
            }
        }
    }

    /**
     * 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)
    {
        $logger = $this->ioc->getService("logger");

        try{
            $response = $this->predictionClient->request('POST', $path, [
                    'json' => $params
            ]);
            return $response;
        }catch(RequestException $e){
            $logger->error(\GuzzleHttp\Psr7\str($e->getRequest()));
            if ($e->hasResponse()) {
                $logger->error(\GuzzleHttp\Psr7\str($e->getResponse()));
            }
        }
    }

}

?>

Test class to cover all the functions in WebHttpClientTest.php.
<?php

use \JobConsumerPHP\IOCUtil;
use function GuzzleHttp\json_decode;

class WebHttpClientTest extends PHPUnit_Framework_TestCase{


protected $webHttpClient;


protected function setUp()
{
$ioc = new IOCUtil();

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

}


public function testDummy()
{
$this->assertTrue(true);

}


public function testPost2Classifier()
{
$path = '/get/job/industry/predictions';

$params = [

'title'=>'senior engineer',



'description'=>'java, scala, python, php, nodejs',



];

$response = $this->webHttpClient->post2Classifier($path, $params);

$this->assertNotEmpty($response);

$this->assertEquals(200, $response->getStatusCode());

$this->assertNotEmpty($response->getBody());

$result = json_decode($response->getBody(), true);

$this->assertNotEmpty($result);

$this->assertTrue(count($result) > 0 );

$this->assertNotEmpty($result[0]);

$this->assertNotEmpty($result[0]['majorCategory']);

}


public function testPost2Prediction()
{
$path = '/v0.9/campaigns/3275/jobPrediction?accountID=0';

$params = [

'applicationName' => 'Sample Application',



'title' => 'Senior Engineer',



'description' => 'Java, Scala, Python, Perl, NodeJS, Groovy, PHP',



'jobCompanyName' => 'Sample Company',



'locations' => [ array("postalCode" => "78729", "postalCode" => "78749") ],



];

$response = $this->webHttpClient->post2Prediction($path, $params);

$this->assertNotEmpty($response);

$this->assertEquals(200, $response->getStatusCode());

$this->assertNotEmpty($response->getBody());





$result = json_decode($response->getBody(), true);

$this->assertNotEmpty($result);

$this->assertTrue(count($result) > 0);

$this->assertNotEmpty($result['jobPredictions']);

$this->assertNotEmpty($result['jobPredictions'][0]);

$this->assertNotEmpty($result['jobPredictions'][0]['suggestedBudget']);

}


}

?>

References:
Redis Command Doc
http://redis.io/commands#sorted_set
Redis PHP Doc
https://github.com/phpredis/phpredis#zrange

https://www.neontsunami.com/posts/how-to-solve-phpunit-exiting-without-errors
分享到:
评论

相关推荐

    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 ...

    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 } } } 其中...

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

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

    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删除 查看此书详细信息请在美国亚马逊官网...

    django-redis组件

    'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PASSWORD': 'your_password', # 如果有密码,添加此项 'PARSER_CLASS': 'redis.connection.HiredisParser', # 使用 hiredis 解析器提升性能 } } } ...

    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, ...

    ZendFramework 1 cache for Redis,Memcached

    5. **使用示例**: 以下是一个基本的 `Redis` 和 `Memcached` 配置和使用示例: ```php // Redis 示例 $redisBackend = Zend_Cache::factory( 'Core', 'Redis', array( 'host' =&gt; 'localhost', 'port' =&gt; ...

    redis的session共享

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

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

    'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } ``` ##### 4.2 配置 Redis 作为会话存储 同样,在 Django 的 settings.py 文件中配置 Redis 会话: ```python SESSION_ENGINE = "django.contrib...

    vagrant-redis-sentinel:Redis和哨兵的游乐场

    无业游民前哨 这是在Vagrant中创建的小型Redis游乐场。... default_backend bk_redis backend bk_redis option tcplog option tcp-check tcp-check send PING\r\n tcp-check expect string +PONG tcp-ch

    statsd-redis-backend:跷跷板

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

    PHP Reactive Programming

    The book will then focus on writing extendable RxPHP code by developing a code testing tool and also cover Using RxPHP on both the server and client side of the application. With a concluding chapter...

    5、redis session 实现Nginx负载均衡多ip同步1

    Redis Session 实现 Nginx 负载均衡多 IP 同步 Redis Session 是一种基于 Redis 的会话管理机制,通过使用 Redis 来存储会话数据,实现了会话的持久化和共享。Nginx 负载均衡是通过使用 Nginx 服务器来实现多个...

    利用redis实现session共享

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

    magehost_cm_cache_backend:MageHost扩展版的Colin Mollenhour的Cm_Cache_Backend_File和Cm_Cache_Backend_Redis

    MageHost_Cm_Cache_Backend MageHost扩展版的Colin Mollenhour的Cm_Cache_Backend_File和Cm_Cache_Backend_Redis安装安装 cd到您的Magento根目录test -d .modman || modman init modman clone --copy --force ...

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

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

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

    'CLIENT_CLASS': 'django_redis.client.SentinelClient', }, } } ``` 这里,'LOCATION'字段指定了Sentinel服务器的地址,'OPTIONS'部分包含了连接Sentinel所需的信息,包括Sentinel主机的列表和密码。 **插件...

    celery定时任务使用总结

    CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # 结果存储的 Redis 连接 URL CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = '...

Global site tag (gtag.js) - Google Analytics