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

PHP Backend Application(3)Solr MySQL Cache

 
阅读更多
PHP Backend Application(3)Solr MySQL Cache

1 Solr
First of all, add the dependency.
> ./composer.phar require solarium/solarium

Clean all SOLR documents
http://xxx.xxx.xxx.xxx:8983/job/update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E&commit=true

Set up Indexer
https://sillycat.atlassian.net/wiki/display/EN/Deploy+a+New+Indexer

SolrSearchClient.php to support adding documents to Solr Server
<?php

namespace JobConsumerPHP;

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

use \Solarium\Client;
use \Solarium\Exception;

class SolrSearchClient
{

    protected $client = null;

    protected $ioc = null;

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

        $this->client = new Client(
                array(
                    'endpoint' => array(
                        'localhost' => array(
                            'host' => ‘xxx.xxx.xxx.xxx',
                            'port' => 8983,
                            'path' => '/job',
                        )
                    )
                )
            );
    }

    public function ping()
    {
        //set up features needed for this method
        $logger = $this->ioc->getService("logger");

        //create a ping query
        $ping = $this->client->createPing();

        //execute the ping query
        try {
            $result = $this->client->ping($ping);
            $logger->debug("Ping query successful-----");
            $logger->debug(var_export($result->getData(), true));
            $logger->debug("--------------------------");
        } catch (Exception $e){
            $logger->error("Ping query failed: " . $e);
        }
    }

    public function addJobDocument($job, $commit)
    {
        //set up features needed for this method
        $logger = $this->ioc->getService("logger");

        //get an update query instance
        $update = $this->client->createUpdate();

        //create a new document for the data
        $doc = $update->createDocument();

        $logger->debug("addJobDocument-----------------");
        while(list($key, $value) = each($job))
        {
            if(is_array($value)){
                //array
                $logger->debug("$key => " . var_export($value, true));
            }else{
                //string
                $logger->debug("$key => $value ");
            }
            $doc->addField($key, $value);
        }
        $logger->debug("-------------------------------");

        try{
            $update->addDocuments(array($doc));
            if($commit)
            {
                $update->addCommit();
                $logger->debug("committing during add documents.");
            }else{
                $logger->debug("NOT committing during add documents.");
            }
            $result = $this->client->update($update);

            $logger->debug("Update query executed---------");
            $logger->debug("Query status: " . $result->getStatus());
            $logger->debug("Query time: " . $result->getQueryTime());
        } catch (Exception $e){
            $logger->error("Add document failed: " . $e);
        }
    }

    public function deleteDocument($jobID)
    {
        //set up features needed for this method
        $logger = $this->ioc->getService("logger");

        //get an update query instance
        $update = $this->client->createUpdate();

        //add the delete query and a commit command to the update query
        $update->addDeleteQuery("id:".$jobID);
        $update->addCommit();

        //this executes the query and returns the result
        $result = $this->client->update($update);

        $logger->debug("Update query executed---------------");
        $logger->debug("Query status: " . $result->getStatus());
        $logger->debug("Query time: " . $result->getQueryTime());
        $logger->debug("------------------------------------");
    }
}
?>

Test Case for that Base Class, SolrSearchClientTest.php
<?php

use \JobConsumerPHP\IOCUtil;

class SolrSearchClientTest extends PHPUnit_Framework_TestCase
{

    protected $solrSearchClient;

    protected function setUp()
    {
        $ioc = new IOCUtil();
        $this->solrSearchClient = $ioc->getService("solrSearchClient");
    }

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

    public function testPing()
    {
        $this->solrSearchClient->ping();
    }

    public function testAddJobDocument()
    {
        $jobProperties = array(
            "id" => "id2",  //required
            "customer_id" => 1,  //required
            "pool_id" => 1,  //required
            "source_id" => 1,  //required
            "url" => "http://url1",
            "company_id" => 1,
            "state_id" => array(
                1,
                2,
                ),
            "zipcode" => array(
                78729,
                78749,
                ),
            "cpc" => 12,
            "reg_cpc" => 10,
            "posted" => "2016-06-23T22:00:00Z",
            "created" => "2016-05-23T22:00:00Z",
            "experience" => 1,
            "salary" => 1,
            "education" => 1,
            "jobtype" => 1,
            "industry" => 1, //main industry
            "industries" => array(
                1,
                2,
                ),  //list of industries
            "quality_score" => 1.0,
            "boost_factor" => 1.0,
            "paused" => false,
            "budget" => 100,
            ..snip...
            );
        $this->solrSearchClient->addJobDocument($jobProperties, true);
    }

    public function testDeleteDocument()
    {
        $jobID = "id2";
        $this->solrSearchClient->deleteDocument($jobID);
    }
}
?>

2 MySQL
MySQLi
http://stackoverflow.com/questions/39753/connection-pooling-in-php

It seems that there is no connection pool in PHP. mysql_pconnect is different.

http://codular.com/php-mysqli

http://cuiqingcai.com/1534.html

http://tao1848.blog.51cto.com/895768/196653

http://www.phpthinking.com/archives/1296

MySQLi Base Class to connect to 3 different DB, MySQLDAO.php
<?php
namespace JobConsumerPHP;
require __DIR__.'/../../vendor/autoload.php';
class MySQLDAO
{
    //job DB info
    protected $jobDBHost = null;
    protected $jobDBName = null;
    protected $jobDBUser = null;
    protected $jobDBPassword = null;
    //stats DB info
    protected $statsDBHost = null;
    protected $statsDBName = null;
    protected $statsDBUser = null;
    protected $statsDBPassword = null;
    //core DB info
    protected $coreDBHost = null;
    protected $coreDBName = null;
    protected $coreDBUser = null;
    protected $coreDBPassword = null;
    protected $ioc = null;
    public function __construct($ioc){
        $this->ioc = $ioc;
        $logger = $this->ioc->getService("logger");
        $config = $this->ioc->getService("config");

        $this->jobDBHost = $config['jobDBHost'];
        $this->jobDBName = $config['jobDBName'];
        $this->jobDBUser = $config['jobDBUser'];
        $this->jobDBPassword = $config['jobDBPassword'];

        $this->statsDBHost = $config['statsDBHost'];
        $this->statsDBName = $config['statsDBName'];
        $this->statsDBUser = $config['statsDBUser'];
        $this->statsDBPassword = $config['statsDBPassword'];

        $this->coreDBHost = $config['coreDBHost'];
        $this->coreDBName = $config['coreDBName'];
        $this->coreDBUser = $config['coreDBUser'];
        $this->coreDBPassword = $config['coreDBPassword'];

        $logger->info("==============MySQL config start ==============");
        $logger->info("jobDBHost = " . $this->jobDBHost);
        $logger->info("jobDBName = " . $this->jobDBName);
        $logger->info("jobDBUser = " . $this->jobDBUser);
        $logger->info("jobDBPassword = " . $this->jobDBPassword);
        $logger->info("===============================================");
        $logger->info("statsDBHost = " . $this->statsDBHost);
        $logger->info("statsDBName = " . $this->statsDBName);
        $logger->info("statsDBUser = " . $this->statsDBUser);
        $logger->info("statsDBPassword = " . $this->statsDBPassword);
        $logger->info("===============================================");
        $logger->info("coreDBHost = " . $this->coreDBHost);
        $logger->info("coreDBName = " . $this->coreDBName);
        $logger->info("coreDBUser = " . $this->coreDBUser);
        $logger->info("coreDBPassword = " . $this->coreDBPassword);
    }

    public function getJobSourceInfoBySourceID($sourceID)
    {
        $query = "
        SELECT
            job_sources.id,
            ..snip...
            job_pools.acct_mgr_id
        FROM
            job_sources
            JOIN job_pools ON pool_id = job_pools.id
            JOIN job_customers ON job_customers.id = job_customer_id
        WHERE
            job_sources.id = ? AND
            status = 1
        ";

        $conn = $this->getJobDBConn();
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $sourceID);
        $stmt->execute();

        $result = $stmt->get_result();
        //$data = $result->fetch_all(MYSQLI_ASSOC);
        //just fetch the first row;
        $data = $result->fetch_assoc();
        $this->closeDBConn($conn);
        return $data;
    }

    private function closeDBConn($conn)
    {
        mysqli_close($conn);
    }

    private function getDBConn($dbHost, $dbName, $dbUser, $dbPass, $dbAlis)
    {
        $logger = $this->ioc->getService("logger");
        $conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
        if(!$conn)
        {
            $logger->error("Fail to connect ". $dbAlis ." DB---------");
            $logger->error($dbAlis . " DBHost = " . $dbHost);
            $logger->error($dbAlis . " DBName = " . $dbName);
            $logger->error($dbAlis . " DBUser = " . $dbUser);
            $logger->error($dbAlis . " DBPassword = " . $dbPass);
        }
        return $conn;
    }

    private function getJobDBConn()
    {
        return $this->getDBConn($this->jobDBHost, $this->jobDBName, $this->jobDBUser, $this->jobDBPassword, "JOB");
    }

    private function getStatsDBconn()
    {
        return $this->getDBConn($this->statsDBHost, $this->statsDBName, $this->statsDBUser, $this->statsDBPassword, "STATS");
    }

    private function getCoreDBConn()
    {
        return $this->getDBConn($this->coreDBHost, $this->coreDBName, $this->coreDBUser, $this->coreDBPassword, "CORE");
    }
}
?>

Test the MySQL Base class, MySQLDAOTest.php
<?php

use \JobConsumerPHP\IOCUtil;

class MySQLDAOTest extends PHPUnit_Framework_TestCase
{
    protected $mySQLDAO;
    protected function setUp()
    {
        $ioc = new IOCUtil();
        $this->mySQLDAO = $ioc->getService("mySQLDAO");
    }
    public function testDummy()
    {
        $this->assertTrue(true);
    }
    public function testGetJobSourceInfoBySourceID()
    {
        $result = $this->mySQLDAO->getJobSourceInfoBySourceID(790);
        $this->assertNotEmpty($result);
    }
}
?>

3 Cache System
https://github.com/gilbitron/PHP-SimpleCache

http://www.phpfastcache.com/

https://github.com/PHPSocialNetwork/phpfastcache/wiki

Redis for that
https://github.com/PHPSocialNetwork/phpfastcache/blob/final/examples/predis.php

> composer require phpFastCache/phpFastCache

The Cache Base Class, FastCache.php
<?php

namespace JobConsumerPHP;
require __DIR__.'/../../vendor/autoload.php';
use \phpFastCache\CacheManager;
class FastCache
{
    protected $cache = null;
    protected $ioc = null;
    public function __construct($ioc){
        $this->ioc = $ioc;
        $logger = $this->ioc->getService("logger");
        $config = $this->ioc->getService("config");
        $logger->info("==============FastCache config start ==========");
        $logger->info("redisHost = " . $config['redisHost']);
        $logger->info("redisPort = " . $config['redisPort']);
        $logger->info("===============================================");
        try {
            CacheManager::setup(array(
                'redis' => array(
                    'host' => $config['redisHost'],
                    'port' => $config['redisPort'],
                    //'password' => '',
                    //'database' => '',
                    //'time' => '',
                    ),
                ));
            $this->cache = CacheManager::getInstance('predis');
            $logger->debug("Successfully connected to Redis and build Cache");
        } catch (Exception $e) {
            $logger->error("Couldn't connected to Redis");
            $logger->error($e->getMessage());
        }
    }
    public function getCache()
    {
        return $this->cache;
    }
}
?>

Test Case class for that, FastCacheTest.php
<?php
use \JobConsumerPHP\IOCUtil;
class FastCacheTest extends PHPUnit_Framework_TestCase
{
    protected $fastCache;
    protected function setUp()
    {
        $ioc = new IOCUtil();
        $this->fastCache = $ioc->getService("fastCache");
    }

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

    public function testCacheAndFetch()
    {
        $key = "cache_key1";
        $value = "cache_value1";
        //seconds
        $this->fastCache->getCache()->set($key, $value, 2);
        $result1 = $this->fastCache->getCache()->get($key);
        $this->assertEquals($value, $result1);
        sleep(3);
        $result2 = $this->fastCache->getCache()->get($key);
        $this->assertEmpty($result2);
    }
}

References:
http://www.solarium-project.org/

http://solarium.readthedocs.io/en/stable/getting-started/

http://solarium.readthedocs.io/en/stable/getting-started/#adding-documents

https://gist.github.com/basdenooijer/894286
分享到:
评论

相关推荐

    Django中的CACHE_BACKEND参数和站点级Cache设置

    ### Django中的CACHE_BACKEND参数和站点级Cache设置 #### CACHE_BACKEND参数详解 在Django中,`CACHE_BACKEND`是一个非常重要的配置项,它用于指定缓存的类型及其相关的配置信息。缓存是提高Web应用性能的关键技术...

    php form generator mysql db backend

    php mysql html form generator using this script you can generate html form for your website and it gives out php script and mysql db schema for you to use with out any coding knowledge

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

    pdns-backend-mysql-4.1.11-1.el7.x86_64.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    Backend_Application

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

    pdns-backend-mysql-4.0.6-2.el7.x86_64.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    开源项目-1backend-1backend.zip

    3. **数据库服务**:作为一个 PaaS 平台,1backend 很可能提供了数据库服务,如 MySQL、PostgreSQL 或 NoSQL 数据库,以便用户可以轻松地存储和访问数据。 4. **身份验证与授权**:安全是任何服务的重要组成部分,1...

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

    server backend3.example.com; } location / { proxy_pass http://backend; } ``` 通过以上步骤,你可以成功搭建一套包含MySQL主从复制、Nginx负载均衡、Redis、PHP和phpredis以及Tomcat的Web服务架构。...

    nginx+apache+mysql+php+memcached+squid搭建门户网站

    ### Nginx+Apache+MySQL+PHP+Memcached+Squid 搭建门户网站 #### 一、前言与架构概述 随着互联网技术的发展,如何构建一个高效、稳定且能够应对高并发访问的Web服务器成为了许多企业和开发者关注的重点。本文将...

    backend-architecture-nodejs-mysql-源码.rar

    标题 "backend-architecture-nodejs-mysql-源码.rar" 暗示了这是一个关于后端架构的项目,使用Node.js作为服务器端编程语言,并且采用了MySQL作为数据库管理系统。这个项目可能包含了实现特定功能的源代码,例如用户...

    Zend Cache:一个实用的缓存php类库

    **3. 使用步骤** - **安装与配置**:通过Composer将Zend Cache添加到项目依赖中,然后根据项目需求配置缓存后端、缓存策略等。 - **初始化缓存**:在PHP代码中创建缓存对象,指定后端类型和配置参数。 - **存储...

    window下手动搭建 PHP+Nginx+Mysql

    3. 完成安装后,通过命令行或MySQL Workbench管理工具连接到MySQL服务器,创建所需的数据库。 **安装Nginx** 1. 解压Nginx的zip文件到任意目录,例如`C:\nginx`。 2. 修改`nginx.conf`配置文件,配置服务器监听的...

    Backend-Mysql-Skills

    后端Mysql技能 请求一个mysql数据库 开发服务器 运行npm run serve如果更改任何源文件,该应用程序将自动重新加载。 NPM模块 mysql2 =&gt; Node.jsMySQL客户端,着重于性能。支持准备好的语句,非utf8编码,二进制日志...

    PHP缓存框架Cachearium.zip

    $cache = CacheAbstract::factory('your backend'); $cache-&gt;store($data, new CacheKey('Namespace', 'Subname')); // get it later try {   $data2 = $cache-&gt;get(new CacheKey('Namespace', '...

    在Android上安装mysql; 从android中访问mysql

    文章"Setting up a linux MySql backend for your Android Application « Hackers Anonymous.htm"可能详细介绍了上述步骤,包括具体的操作指南和注意事项。文件名中的"_files"可能包含相关的图片、示例代码或其他...

    Backend-repository:学习PHP + MySQL

    【标题】"Backend-repository:学习PHP + MySQL" 指的是一个专注于后端开发的学习资源库,特别强调了PHP和MySQL这两种技术的结合。PHP是一种广泛使用的服务器端脚本语言,尤其适合Web开发,而MySQL则是一款流行的关系...

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

    PyPI 官网下载 | django_minio_backend-2.7.0-py3-none-any.whl

    标题"PyPI 官网下载 | django_minio_backend-2.7.0-py3-none-any.whl"表明这是一个从Python的官方包仓库PyPI上下载的软件包,名为`django_minio_backend`,版本为2.7.0,适用于Python 3环境,且不分平台(`py3-none-...

    使用mysql-proxy实现mysql读写分离

    3. **安装mysql-proxy**:按照文档中的步骤完成mysql-proxy的安装。 4. **配置mysql-proxy**:通过命令行指定mysql-proxy的工作参数,例如主库和从库的地址、端口等。 ```bash /usr/local/mysql-proxy/sbin/...

Global site tag (gtag.js) - Google Analytics