- 浏览: 2539416 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 Connect Redis Driver
I was using Predis before. But it seems that our company is using another one in the common codes. So I plan to follow that and use that one instead.
https://github.com/phpredis/phpredis#readme
Installation
> git clone https://github.com/phpredis/phpredis
> cd phpredis/
> phpize
> ./configure
> make
> sudo make install
After installation, we can try these classes as follow:
<?php
namespace BillingConsumerPHP;
require __DIR__.'/../../vendor/autoload.php';
use \Redis;
class PHPRedisClient
{
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 Redis();
$this->client->pconnect($config['redisHost'], $config['redisPort'], 0.5);
$logger->debug("Successfully connected to Redis");
}
catch (Exception $e)
{
$logger->error("Couldn't connected to Redis");
$logger->error($e->getMessage());
}
}
public function isRecoverNeeded(){
$max = $this->client->get("job_id_counter");
//if counter is 0 or empty, redis already crashed.
return $max <= 4294967295;
}
public function incrJobIDCounter(){
return $this->client->incr("job_id_counter");
}
public function getJobIDCounter(){
return $this->client->get("job_id_counter");
}
public function setJobIDCounter($number){
$this->client->set("job_id_counter", $number);
}
public function cleanJobIDCounter(){
$this->client->del("job_id_counter");
}
public function incrAndFetchSpend($jobID, $date, $spend){
$dateTimeUtil = $this->ioc->getService("dateTimeUtil");
//life time spend
$lifeTimeSpend = $this->client->hincrby("job_budget_{$jobID}", 'lifetimespend', $spend);
//daily spend
$dateString = $dateTimeUtil->getDateString($date);
$dailySpend = $this->client->hincrby("job_dailyspend_{$jobID}", $dateString, $spend);
//monthly spend
$monthString = $dateTimeUtil->getMonthString($date);
$monthlySpend = $this->client->hincrby("job_monthlyspend_{$jobID}", $monthString, $spend);
return array(
'lifeTimeSpend'=>$lifeTimeSpend,
'dailySpend'=>$dailySpend,
'monthlySpend'=>$monthlySpend,
);
}
public function updateJobIDMapping($jobIDMappings){
foreach ($jobIDMappings as $jobIDMap){
$sourceID = $jobIDMap['source_id'];
$referenceID = $jobIDMap['job_reference'];
$jobID = $jobIDMap['job_id'];
//step1 sourceID_referenceID => jobID => value
$jobSourceKey = "job_{$sourceID}_{$referenceID}";
$columnName = "job_id";
$this->client->hset($jobSourceKey, $columnName, $jobID);
//step2 jobID => sourceID_referenceID
$redisKey = "idmapping_{$jobID}";
$redisValue = "{$sourceID}_{$referenceID}";
$this->client->set($redisKey, $redisValue);
}
}
public function getJobIDMapping($jobID)
{
$redisKey = "idmapping_{$jobID}";
$redisValue = $this->client->get($key);
if(null !== $redisValue){
$infos = explode("_", $redisValue);
if(count($infos) > 1){
return array(
'sourceID' => $infos[0],
'referenceID' => $infos[1],
);
}else{
return null;
}
}else{
return null;
}
}
public function updateHistoryDailySpending($spendings){
foreach ($spendings as $spend){
$jobID = $spend['job_id'];
$redisKey = "job_dailyspend_{$jobID}";
$redisColumn = $spend['date'];
$redisValue = $spend['spend']; //m cents
$this->client->hincrbyfloat($redisKey, $redisColumn, $redisValue);
}
}
public function updateHistoryMonthlySpending($spendings){
foreach ($spendings as $spend){
$jobID = $spend['job_id'];
$redisValue = $spend['spend'] * 1000; //m cents
$month = $spend['month'];
$redisKey = "job_monthlyspend_{$jobID}";
$redisColumn = $month;
$this->client->hincrbyfloat($redisKey, $redisColumn, $redisValue);
}
}
public function getBudget($jobID){
$result = $this->client->hmget("job_budget_{$jobID}", array('budget', 'budgetType'));
return $result;
}
public function sendRawJobContent($key, $message){
$logger = $this->ioc->getService("logger");
//send to redis
$this->client->setEx($key, TIME_3DAY, $message);
}
}
?>
This class can be tested by phpunit
<?php
use \BillingConsumerPHP\IOCUtil;
/**
* RUNNING_ENV=test phpunit --bootstrap vendor/autoload.php tests/BillingConsumerPHP/PHPRedisClientTest
* @author carl
*/
class PHPRedisClientTest extends PHPUnit_Framework_TestCase
{
private $phpRedisClient;
protected function setUp()
{
$ioc = new IOCUtil();
$this->phpRedisClient = $ioc->getService("phpRedisClient");
}
public function testDummy()
{
$this->assertTrue(true);
}
public function testDailySpending(){
$jobIDs = "4294967295";
$date = "2016-08-22";
$spending = 12.34;
$spendings = array();
for($i = 0; $i<10; $i++){
$spendings[] = array(
'job_id' => $jobIDs . $i,
'date' => $date,
'spend' => $spending,
);
}
$this->phpRedisClient->updateHistoryDailySpending($spendings);
}
public function testCrash(){
$this->phpRedisClient->cleanJobIDCounter();
$result1 = $this->phpRedisClient->isRecoverNeeded();
$this->assertTrue($result1);
$this->phpRedisClient->setJobIDCounter(12);
$result2 = $this->phpRedisClient->isRecoverNeeded();
$this->assertTrue($result2);
$this->phpRedisClient->setJobIDCounter(42949672951);
$result3 = $this->phpRedisClient->isRecoverNeeded();
$this->assertFalse($result3);
}
}
?>
I am always using docker image to deploy my things. Actually, comparing Predis which is not an extension, the installation of extension is a little complex.
Dockerfile
#install Redis Native PHP Client
RUN yum install -y git
RUN git clone https://github.com/phpredis/phpredis
WORKDIR /install/phpredis
RUN phpize
RUN ./configure
RUN make
RUN make install
And we have to add extension configuration in php.ini
extension=iconv.so
extension=raphf.so
extension=propro.so
extension=http.so
extension=redis.so
References:
http://www.thegeekstuff.com/2014/02/phpredis/
I was using Predis before. But it seems that our company is using another one in the common codes. So I plan to follow that and use that one instead.
https://github.com/phpredis/phpredis#readme
Installation
> git clone https://github.com/phpredis/phpredis
> cd phpredis/
> phpize
> ./configure
> make
> sudo make install
After installation, we can try these classes as follow:
<?php
namespace BillingConsumerPHP;
require __DIR__.'/../../vendor/autoload.php';
use \Redis;
class PHPRedisClient
{
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 Redis();
$this->client->pconnect($config['redisHost'], $config['redisPort'], 0.5);
$logger->debug("Successfully connected to Redis");
}
catch (Exception $e)
{
$logger->error("Couldn't connected to Redis");
$logger->error($e->getMessage());
}
}
public function isRecoverNeeded(){
$max = $this->client->get("job_id_counter");
//if counter is 0 or empty, redis already crashed.
return $max <= 4294967295;
}
public function incrJobIDCounter(){
return $this->client->incr("job_id_counter");
}
public function getJobIDCounter(){
return $this->client->get("job_id_counter");
}
public function setJobIDCounter($number){
$this->client->set("job_id_counter", $number);
}
public function cleanJobIDCounter(){
$this->client->del("job_id_counter");
}
public function incrAndFetchSpend($jobID, $date, $spend){
$dateTimeUtil = $this->ioc->getService("dateTimeUtil");
//life time spend
$lifeTimeSpend = $this->client->hincrby("job_budget_{$jobID}", 'lifetimespend', $spend);
//daily spend
$dateString = $dateTimeUtil->getDateString($date);
$dailySpend = $this->client->hincrby("job_dailyspend_{$jobID}", $dateString, $spend);
//monthly spend
$monthString = $dateTimeUtil->getMonthString($date);
$monthlySpend = $this->client->hincrby("job_monthlyspend_{$jobID}", $monthString, $spend);
return array(
'lifeTimeSpend'=>$lifeTimeSpend,
'dailySpend'=>$dailySpend,
'monthlySpend'=>$monthlySpend,
);
}
public function updateJobIDMapping($jobIDMappings){
foreach ($jobIDMappings as $jobIDMap){
$sourceID = $jobIDMap['source_id'];
$referenceID = $jobIDMap['job_reference'];
$jobID = $jobIDMap['job_id'];
//step1 sourceID_referenceID => jobID => value
$jobSourceKey = "job_{$sourceID}_{$referenceID}";
$columnName = "job_id";
$this->client->hset($jobSourceKey, $columnName, $jobID);
//step2 jobID => sourceID_referenceID
$redisKey = "idmapping_{$jobID}";
$redisValue = "{$sourceID}_{$referenceID}";
$this->client->set($redisKey, $redisValue);
}
}
public function getJobIDMapping($jobID)
{
$redisKey = "idmapping_{$jobID}";
$redisValue = $this->client->get($key);
if(null !== $redisValue){
$infos = explode("_", $redisValue);
if(count($infos) > 1){
return array(
'sourceID' => $infos[0],
'referenceID' => $infos[1],
);
}else{
return null;
}
}else{
return null;
}
}
public function updateHistoryDailySpending($spendings){
foreach ($spendings as $spend){
$jobID = $spend['job_id'];
$redisKey = "job_dailyspend_{$jobID}";
$redisColumn = $spend['date'];
$redisValue = $spend['spend']; //m cents
$this->client->hincrbyfloat($redisKey, $redisColumn, $redisValue);
}
}
public function updateHistoryMonthlySpending($spendings){
foreach ($spendings as $spend){
$jobID = $spend['job_id'];
$redisValue = $spend['spend'] * 1000; //m cents
$month = $spend['month'];
$redisKey = "job_monthlyspend_{$jobID}";
$redisColumn = $month;
$this->client->hincrbyfloat($redisKey, $redisColumn, $redisValue);
}
}
public function getBudget($jobID){
$result = $this->client->hmget("job_budget_{$jobID}", array('budget', 'budgetType'));
return $result;
}
public function sendRawJobContent($key, $message){
$logger = $this->ioc->getService("logger");
//send to redis
$this->client->setEx($key, TIME_3DAY, $message);
}
}
?>
This class can be tested by phpunit
<?php
use \BillingConsumerPHP\IOCUtil;
/**
* RUNNING_ENV=test phpunit --bootstrap vendor/autoload.php tests/BillingConsumerPHP/PHPRedisClientTest
* @author carl
*/
class PHPRedisClientTest extends PHPUnit_Framework_TestCase
{
private $phpRedisClient;
protected function setUp()
{
$ioc = new IOCUtil();
$this->phpRedisClient = $ioc->getService("phpRedisClient");
}
public function testDummy()
{
$this->assertTrue(true);
}
public function testDailySpending(){
$jobIDs = "4294967295";
$date = "2016-08-22";
$spending = 12.34;
$spendings = array();
for($i = 0; $i<10; $i++){
$spendings[] = array(
'job_id' => $jobIDs . $i,
'date' => $date,
'spend' => $spending,
);
}
$this->phpRedisClient->updateHistoryDailySpending($spendings);
}
public function testCrash(){
$this->phpRedisClient->cleanJobIDCounter();
$result1 = $this->phpRedisClient->isRecoverNeeded();
$this->assertTrue($result1);
$this->phpRedisClient->setJobIDCounter(12);
$result2 = $this->phpRedisClient->isRecoverNeeded();
$this->assertTrue($result2);
$this->phpRedisClient->setJobIDCounter(42949672951);
$result3 = $this->phpRedisClient->isRecoverNeeded();
$this->assertFalse($result3);
}
}
?>
I am always using docker image to deploy my things. Actually, comparing Predis which is not an extension, the installation of extension is a little complex.
Dockerfile
#install Redis Native PHP Client
RUN yum install -y git
RUN git clone https://github.com/phpredis/phpredis
WORKDIR /install/phpredis
RUN phpize
RUN ./configure
RUN make
RUN make install
And we have to add extension configuration in php.ini
extension=iconv.so
extension=raphf.so
extension=propro.so
extension=http.so
extension=redis.so
References:
http://www.thegeekstuff.com/2014/02/phpredis/
发表评论
-
PHP Command Line Tool
2019-08-17 05:06 386PHP Command Line Tool Recently ... -
Code SonarQube 2019(2)PostgreSQL as Database
2019-07-24 05:32 418Code SonarQube 2019(2)PostgreSQ ... -
Code SonarQube 2019(1)Installation with default H2
2019-07-23 10:42 765Code SonarQube 2019(1)Installat ... -
Auth Solution(3)JWT in Java and PHP Sample
2019-05-03 07:33 307Auth Solution(3)JWT in Java and ... -
Flarum BBS System(2)Docker the BBS
2018-11-20 03:31 643Flarum BBS System(2)Docker the ... -
Flarum BBS System(1)Installation and Introduction
2018-11-18 14:29 496Flarum BBS System(1)Installatio ... -
Grav CMS System(5)Multiple Domains and Certs
2018-11-15 01:48 526Grav CMS System(5)Multiple Doma ... -
Grav CMS System(4)Multiple Domain Sites in HAProxy and HTTPS
2018-11-14 21:33 572Grav CMS System(4)Multiple Doma ... -
Grav CMS System(3)Docker Nginx and PHP
2018-11-14 00:21 455Grav CMS System(3)Docker Nginx ... -
Grav CMS System(1)Install PHP7 on MAC
2018-10-23 21:53 613Grav CMS System(1)Install PHP7 ... -
Laravel PHP Framework(1)Introduction and Installation
2018-08-22 02:47 979Laravel PHP Framework(1)Introdu ... -
JSON Log in PHP and Cloud Watch(1)JSON Format in PHP
2017-12-30 05:31 597JSON Log in PHP and Cloud Watch ... -
PHPRedis Library
2017-03-30 00:32 673PHPRedis Library We can instal ... -
PHP Call Wget Command
2017-03-24 23:35 665PHP Call Wget Command In my PH ... -
PHP XML Writer
2017-03-10 03:59 1446PHP XML Writer PHP XML writer ... -
PHP Redis Client and Cluster
2017-02-16 03:34 643PHP Redis Client and Cluster S ... -
PHP Redis Client and Replica
2017-02-16 01:11 588PHP Redis Client and Replica W ... -
PHP HTTP Library and Error Handling
2017-02-11 06:19 636PHP HTTP Library and Error Hand ... -
PHP ENV and HTTP Extension
2017-01-12 01:04 787PHP ENV and HTTP Extension We ... -
Batch Insert in PHP MySQLi
2016-08-24 00:58 697Batch Insert in PHP MySQLi Whe ...
相关推荐
$config['sess_driver'] = 'redis'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 0; $config['sess_save_path'] = 'tcp://***.*.*.*:6379'; ``` 这样配置之后,CodeIgniter框架在...
导语 经过编译安装和安装扩展之后,Redis 已经可以正常使用了。... 设置 Cache 默认缓存为 Redis,在 .evn 文件中 CACHE_DRIVER=redis; 设置 Session 的驱动为 Redis,在 .env 文件中 SESSION_DR
ThinkPHP框架的Library目录下提供了对Redis操作的封装类,位于Think\Cache\Driver\Redis.class.php路径下。这个类封装了Redis的基本操作命令,使得开发者可以在ThinkPHP框架中方便地使用Redis的特性。 例如,首先...
这可以通过编写自定义的`Connector`实现,或者在`QueueManager`的`connect`方法中动态判断。 例如,我们可以在`app/Providers/AppServiceProvider.php`的`boot`方法中添加以下代码: ```php public function boot()...
$connection = $connector->connect($config); $stores[$store] = new TaggableStore( $app['cache.repository']->getTagSet(), $connection, $config['prefix'] ); } } return $stores; }); } public ...
Laravel 5.3及以上版本引入了广播系统,它允许开发者将事件数据推送到多种不同的实时后端,如Pusher、Redis或Centrifuge。Centrifuge是一个强大的实时消息传递服务器,支持WebSocket、Long Polling等多种传输协议。 ...
Laravel广播支持多种驱动器,包括Pusher、Redis、Broadcast和Faye。在这个案例中,我们关注的是Faye驱动器。 安装"Faye Laravel Broadcaster"首先需要通过Composer进行,使用以下命令: ```bash composer require ...
在`.env`文件中,将`BROADCAST_DRIVER`设置为`redis`,并创建一个自定义的事件类,例如`WechatLoginedEvent`,实现`ShouldBroadcast`接口,这样当用户微信登录时,该事件会被广播出去。 ```php // ...