• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            xiaoguozi's Blog
            Pay it forword - 我并不覺的自豪,我所嘗試的事情都失敗了······習慣原本生活的人不容易改變,就算現狀很糟,他們也很難改變,在過程中,他們還是放棄了······他們一放棄,大家就都是輸家······讓愛傳出去,很困難,也無法預料,人們需要更細心的觀察別人,要隨時注意才能保護別人,因為他們未必知道自己要什么·····

            Recently I've come face-to-face with a significant processing task for a web application written in PHP.  I haven't worked with process control very much, so I started researching ways of distributing the calculations to multiple processes.  PHP offers several libraries for doing this (pcntl, POSIX), but it quickly became clear that if you're running Windows these libraries are not an option, and unfortunately at work I have a Windows machine.  After a lot more research, I came across Gearman.

            Gearman is essentially a distributed processing framework, and seems to have community support for many programming languages.  It consists of two main components: the job server, and a Client and Worker API.  The Client and Worker API can be used in a wide variety of languages, but the job server is only available as a C library or a Perl library.  This makes it a bit tougher to get the server running on Windows, especially when you start running into some of the dependencies that it requires to build.  As well, the Client/Worker API for PHP can only be installed as a PECL extension, or a very-out-of-date PEAR extension called Net_Gearman.

            Nonetheless, after yet more research I decided that I would give it a shot by using Cygwin to get the job server running (if you haven't used Cygwin before, be sure to read about it before attempting to install Gearman this way), and PEAR to use the API.  Pre-built PECL extensions aren't available for Windows anymore, and the build process for PHP extensions can be pretty painful, so it makes PEAR look good by comparison even if the code will be out of date.

            I had a pretty frustrating time finally getting everything up and running due to various dependency issues, so I went back through the whole process and wrote it out step-by-step.  I used a Windows XP SP3 machine for this, but I also got it working on a Windows 7 machine as well.

            Installing the Gearman job server (gearmand) on Windows with Cygwin

            Installing Cygwin

            1. If you don't have Cygwin already, you can get it from http://www.cygwin.com.  The setup file is located here, and the setup process is pretty straightforward; run it and follow the wizard.  Full installation instructions are available at the Cygwin site.
            2. Keep the Cygwin setup.exe file handy after you've installed the default software packages, as you'll need it in the future to add packages, similar to apt-get, yum, and other Linux/UNIX package managers.
            3. Cygwin installs with some basic packages, including a Cygwin Bash Shell that goes into your Start Menu.  I prefer the mintty emulator instead, as it has less of a DOS Command Prompt feel and better terminal features.  Feel free to use whatever shell you like of course.  You can get mintty by re-running the setup.exe, and at the package selection screen, type 'mintty' into the Search bar at the top left.  Expand the "Shells" category, and click on the word "Skip" under the "New" column beside the mintty package to select it before continuing the install process.

            Installing Cygwin Package Dependencies needed for Gearman

            If you're not already in the Cygwin setup, re-run the Cygwin setup.exe and go through to the package selection screen.  The following is a list of dependency packages you will need in order to build the Gearman job server (gearmand).  None of these packages were installed by default with Cygwin:

            • gcc
            • make
            • libuuid1-devel
            • libiconv

            There's a good installation tutorial here that walks through getting gcc and make installed for people unfamiliar with Cygwin.  Finding the others is pretty straightforward, the Search bar in the package selector works well.

            Installing libevent

            Gearmand requires an event notification library called libevent that you cannot get as a Cygwin package, which means it has to be installed from source.  You can get the source here.

            1. Download and unpack the latest libevent stable release.  At the time of this writing, I used libevent-1.4.14b-stable.
              NOTE: Download and unpack to a directory that does not contain spaces in the name, such as "C:/cygwin/home/Zombat/libevent-1.4.14b-stable".  If you unpack to something with spaces like "C:/Documents and Settings/Zombat/", the build process might not be able to install libevent correctly (libtool has a hard time with spaces)!
            2. Open a Cygwin shell and cd to the unpacked libevent directory.
            3. Run the following commands:

            ./configure
            make
            make install

            libevent should now be installed and ready to be used when compiling the Gearman job server.

            Installing the Gearman job server, gearmand.exe

            1. Download and unpack the C implementation of gearmand from http://gearman.org/index.php?id=download
            2. Open a cygwin shell and cd to your unpacked gearmand directory.  Same rules apply as before, make sure you've unpacked in a directory with no spaces in the path!  libtool hates that, and your build may fail.
            3. Run the following commands:

            ./configure
            make
            make install

            The Gearman job server should now be installed and ready to use!  Mine was installed at /usr/local/sbin/gearmand.exe, and running it with a "triple verbose" flag (-vvv) should produce the following:

            gearmand.exe startup debug output

            That's it for the job server.  When you want to start it, simply open a Cygwin shell and run gearmand.exe.  Running it with the -d flag will cause the server to run as a daemon in the background, and running with --help will show you the full option list.

            Installing the Gearman Client and Worker API (Net_Gearman)

            I chose to install the PEAR Client and Worker API, as it is native PHP and doesn't involve compiling PECL extensions.  The PEAR package is called Net_Gearman, and was originally written by Joe Stump at Digg.com.  It is old and out of date now, although there appears to be a more recent fork at http://github.com/brianlmoon/net_gearman.  I stuck with the older version, as I suspect it will meet my needs, and was readily available as a PEAR package.

            This also makes installation relatively painless.  Assuming you've previously set PEAR up, then all you have to do is open a command window (not a Cygwin shell) and run:

            pear install Net_Gearman-alpha

            The "-alpha" portion is necessary, as Net_Gearman apparently never made it to a stable release version.  That being said, it has functioned well for me so far.  Perhaps someone will pick the project up in the future.

            I'll write more about getting started with the Client and Worker API in the next article, so we can actually use Gearman to get some work done.

            轉自:
            http://www.phpvs.net/2010/11/30/installing-gearman-and-gearmand-on-windows-with-cygwin/
            posted @ 2012-12-28 11:17 小果子 閱讀(2612) | 評論 (0)編輯 收藏

            Gearman是一個分布式的任務調度框架,它包括 a client,a worker ,a job server這三部分組成。

            Gearman的執行過程:客戶端通過客戶端API(PHP,C,Perl等)創建一個任務發送到job server上,Job Server 通過客戶端的function name 查找合適的worker,并分到該worker上,worker接收到任務后根據worker的規則執行,并返回數據到job Server,而Job Server則把數據返回給客戶端,這樣Gearman的執行過程就結束了。

            用戶可以根據不同的需求制定不同的worker來處理不同的任務,將這些worker存放到不同的服務器上,Job Server會根據不同的客戶端發送來的任務的function name尋找worker來執行,從而達到為業務服務器減輕壓力;

            Gearman的安裝:

            下載http://launchpad.net/gearmand/trunk/0.12/+download/gearmand-0.12.tar.gz



            [falcon@www-001  ~/src/]$ wget http://launchpad.net/gearmand/tr ... earmand-0.12.tar.gz
            [falcon@www-001  ~/src/]$ cd gearmand-0.12

            [falcon@www-001  ~/src/gearmand-0.12]$ ./configure --prefix=/home/falcon/gearmand

            [falcon@www-001  ~/src/gearmand-0.12]$ make && make instal

            運行gearman 的job Server


            [falcon@www-001  ~/src/gearmand-0.12]$ cd ~/gearmand

            [falcon@www-001  ~/gearmand]$ ls
            bin  include  lib  sbin  share
            [falcon@www-001  ~/gearmand]$ sbin/gearmand --help
            gearmand 0.12 - https://launchpad.net/gearmand
            usage: sbin/gearmand
            [OPTIONS]Main Options:
            -b, --backlog=BACKLOG       Number of backlog connections for listen.
            -d, --daemon                Daemon, detach and run in the background.
            -f, --file-descriptors=FDS  Number of file descriptors to allow for the process                             
            (total connections will be slightly less). Default     is max allowed for user.
            -h, --help                  Print this help menu.
            -j, --job-retries=RETRIES   Number of attempts to run the job before the job  server removes it. Thisis helpful to ensure a bad  job does not crash all available workers. Default  is no limit.
            -l, --log-file=FILE         Log file to write errors and information to. Turning this option on also forces the first  verbose level to be enabled.
            -L, --listen=ADDRESS        Address the server should listen on. Default is  INADDR_ANY.
            -p, --port=PORT             Port the server should listen on.
            -P, --pid-file=FILE         File to write process ID out to.
            -r, --protocol=PROTOCOL     Load protocol module.
            -R, --round-robin           Assign work in round-robin order per  workerconnection. The default is to assign work in  the order of functions added by the worker.
            -q, --queue-type=QUEUE      Persistent queue type to use.
            -t, --threads=THREADS       Number of I/O threads to use. Default=0.
            -u, --user=USER             Switch to given user after startup.
            -v, --verbose               Increase verbosity level by one.
            -V, --version               Display the version of gearmand and exit.
            -w, --worker-wakeup=WORKERS Number of workers to wakeup for each job received.   The default is to wakeup all available workers.



            運行Job Server服務

            [falcon@www-001  ~/gearmand]$ sbin/gearmand -d



            判斷gearmand是否運行

            [falcon@www-001  ~/gearmand]$ ps -ef|grep gearmand

            falcon    9083     1  0 02:46 ?        00:00:00 sbin/gearmand -d -vv

            falcon    9112 28298  0 02:47 pts/1    00:00:00 grep gearmand

            [falcon@www-001  ~/gearmand]$ netstat -an -t|grep 4730

            tcp        0      0 0.0.0.0:4730                0.0.0.0:*                   LISTEN  



            到此Job Server運行正常,下面我們可以簡單的在本地上測試Worker和Client是否能夠正常接收任務

            我們這里用gearman命令來測試

            [falcon@www-001  ~/gearmand]$ bin/gearman --help

            bin/gearman: invalid option -- -

            Client mode: bin/gearman [options] [<data>]

            Worker mode: bin/gearman -w [options] [<command> [<args> ...]]

            公共參數區

            Common options to both client and worker modes.  

                    -f <function> - Function name to use for jobs (can give many)處理任務的函數名

                    -h <host>     - Job server host  (Job Server主機,默認是localhost)

                    -H            - Print this help menu

                    -p <port>     - Job server port (Job Server端口,默認是4730)

                    -t <timeout>  - Timeout in milliseconds  (執行多長時間超時,微秒)

                    -i <pidfile>  - Create a pidfile for the process (創建進程的pid文件)

            Client部分參數

            Client options:

                    -b            - Run jobs in the background (后臺運行任務)

                    -I            - Run jobs as high priority (高優先級運行任務)

                    -L            - Run jobs as low priority (低優先級運行任務)

                    -n            - Run one job per line (逐行執行任務)

                    -N            - Same as -n, but strip off the newline  

                    -P            - Prefix all output lines with functions names (在輸入結果前面加處理的函數名)

                    -s            - Send job without reading from standard input 執行任務不返回結果

                    -u <unique>   - Unique key to use for job 任務的唯一標識

            Worker部分參數

            Worker options:

                    -c <count>    - Number of jobs for worker to run before exiting (統計worker進程處理多少個任務后中止)

                    -n            - Send data packet for each line

                    -N            - Same as -n, but strip off the newline

                    -w            - Run in worker mode   以worker模式運行




            示例一、以命令行方式模擬worker 和 client來處理任務

            開啟一個worker,以function name 為 tongji 來處理輸入的數據,統計行數并返回結果

            [falcon@www-001  ~/gearmand]$ bin/gearman -w -f tongji -- wc -l  

            模擬客戶端連接到Job Server,以tongji函數名來提交一個文件,并接收結果

            [falcon@www-001  ~/gearmand]$ bin/gearman -f tongji  < /etc/profile

            54




            示例二、利用Gearman的php擴展來測試Gearman



            安裝PHP的Gearman擴展模塊

            [falcon@www-001  ~/src]$ wget  http://pecl.php.net/get/gearman-0.7.0.tgz

            [falcon@www-001  ~/src]$ cd gearman-0.7.0

            [falcon@www-001  ~/src/gearman-0.7.0]$ /home/falcon/php/bin/phpize

            ......

            [falcon@www-001  ~/src/gearman-0.7.0]$ ./configure \

            --with-php-config=/home/falcon/php/bin/php-config --with-gearman=/home/falcon/gearmand

            [falcon@www-001  ~/src/gearman-0.7.0]$ make && make install

            將gearman.so加入到php.ini配置文件使其生效

            測試php是否加載gearman模塊



            [falcon@www-001  ~/php/bin]$ php -m|grep gearman




            官方示例:

            將提交的字符串翻轉后返回



            Worker :worker_reverse.php



            <?php

            $worker= new GearmanWorker();

            $worker->addServer();

            $worker->addFunction("reverse", "my_reverse_function");

            while ($worker->work());


            function my_reverse_function($job)

            {

              return strrev($job->workload());

            }

            ?>


            運行worker

            $php work_reverse.php &




            Client:client_reverse.php



            <?php

            $client= new GearmanClient();

            $client->addServer();

            print $client->do("reverse", "Hello World!");

            ?>


            執行client_reverse.php



            $ php client_reverse.php

            !dlroW olleH

            參考資料:


            http://gearman.org/index.php?id=getting_started


            http://pecl.php.net/package/gearman


            http://www.ibm.com/developerworks/cn/opensource/os-php-gearman/
            posted @ 2012-12-27 20:19 小果子 閱讀(1928) | 評論 (0)編輯 收藏

            Some times the core validation rules provided by Yii won't satisfy all your needs, so you'll need to create your very own validation rule.

            Easy approach: inside-model rule

            The easiest way to create a new validation rule is inside the model that is going to use it.

            Let's say that you want to check if a user password is safe enough.
            Usually you could achieve this result just by using the CRegularExpressionValidator but for the sake of this guide let's pretend that validator does not exist.

            first of all in your model class you'll have to add two constants

            const WEAK = 0; const STRONG = 1;

            then in your rules method you'll have to set the rule

            /**  * @return array validation rules for model attributes.  */ public function rules() {     return array(        array('password', 'passwordStrength', 'strength'=>self::STRONG),     ); }

            make sure that you won't give the rule the name of an existing one, otherwise you are going to have some troubles later.

            Now the only thing you need to do is create a new method inside the model, named after the validation rule you just declared.

            /**  * check if the user password is strong enough  * check the password against the pattern requested  * by the strength parameter  * This is the 'passwordStrength' validator as declared in rules().  */ public function passwordStrength($attribute,$params) {     if ($params['strength'] === self::WEAK)         $pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';       elseif ($params['strength'] === self::STRONG)         $pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';         if(!preg_match($pattern, $this->$attribute))       $this->addError($attribute, 'your password is not strong enough!'); }

            The new method you just created accepts two arguments:

            • $attribute = is the name of the attribute that the method is validating
            • $params = additional parameters that you could define in the rules

            In our rules method we used this rule on the password attribute, so the value of attribute inside our validation model will be password

            In the rule we also setted an additional parameter named strength
            the value of that parameter will be inside the $params array

            As you can see inside the method we are making a call to CModel::addError().
            Add Error accepts two parameters: the first one is the name of the attribute that you want to display the error in your form, the second one is the actual error string you want to be displayed.

            Complete approach: extending the CValidator class

            If you need your custom validation rule in more then one model the best thing to do is extending the CValidator class.
            Extending this class you also can take advantage of other features, like CActiveForm::$enableClientValidation, first implemented with Yii 1.1.7 release.

            Creating the class file

            The first thing that you have to do is create your class file. The best thing is to always name it after your class name, to best use Yii lazy loading feature. Let's create a new directory inside your application extensions directory (which is located inside the protected directory).
            Name this directory MyValidators.
            Then we create our own file: passwordStrength.php

            Inside this file create our CValidator class

            class passwordStrength extends CValidator {       public $strength;       private $weak_pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';     private $strong_pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/'; ...

            In the class file create one attribute for each additional parameter that you want to use inside your validation rule.
            CValidator will take care to populate that attribute with the parameter value all by itself.
            We also created two other attributes, each containing the patterns we want to use in our preg_match function.

            Now we have to override the parent abstract method validateAttribute

            /**  * Validates the attribute of the object.  * If there is any error, the error message is added to the object.  * @param CModel $object the object being validated  * @param string $attribute the attribute being validated  */ protected function validateAttribute($object,$attribute) {     // check the strength parameter used in the validation rule of our model     if ($this->strength == 'weak')       $pattern = $this->weak_pattern;     elseif ($this->strength == 'strong')       $pattern = $this->strong_pattern;       // extract the attribute value from it's model object     $value=$object->$attribute;     if(!preg_match($pattern, $value))     {         $this->addError($object,$attribute,'your password is too weak!');     } }

            The method above is self explanatory i think.
            Of course you could use constants in those IF, and I actually recommend it.

            Implementing Client Validation

            If you want to implement client validation you'll need to override another method inside your class: clientValidateAttribute

            /**  * Returns the JavaScript needed for performing client-side validation.  * @param CModel $object the data object being validated  * @param string $attribute the name of the attribute to be validated.  * @return string the client-side validation script.  * @see CActiveForm::enableClientValidation  */ public function clientValidateAttribute($object,$attribute) {       // check the strength parameter used in the validation rule of our model     if ($this->strength == 'weak')       $pattern = $this->weak_pattern;     elseif ($this->strength == 'strong')       $pattern = $this->strong_pattern;            $condition="!value.match({$pattern})";       return " if(".$condition.") {     messages.push(".CJSON::encode('your password is too weak, you fool!')."); } "; }

            As you can see this method simply returns the javascript that you need to use for your validation

            Last step: how to use your validation class inside the module rules

            There are several approach you can use here.

            You could first use Yii::import in the rules method before returning the rules array, or you can just use Yii dot notation:

            /**  * @return array validation rules for model attributes.  */ public function rules() {     return array(        array('password', 'ext.MyValidators.passwordStrength', 'strength'=>self::STRONG),     ); }
            more:
            http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
            posted @ 2012-12-26 15:39 小果子 閱讀(505) | 評論 (0)編輯 收藏

            Yii supports AJAX form validation, which essentially posts the form values to the server, validates them, and sends back the validation errors, all without leaving the page. It does this every time you tab out of a (changed) field.

            As of 1.1.7, Yii supports regular Javascript validation in addition to AJAX validation, but I'll talk about that in another post.

            Here's how Yii's AJAX validation works:

            1. in your yii form declaration, put:
              <php $form = $this->beginWidget('CActiveForm', array(
              'id'=>'lowercasemodelname-form', //not technically required but works w gii generated controllers
              'enableAjaxValidation'=>true //turn on ajax validation on the client side )); 
              And have at least one form element with a matching error function:
              <?php echo $form->textField($model, 'my_attribute'); ?>
              <?php echo $form->error($model, 'my_attribute'); ?> 
              This makes Yii include the JQuery javascript library, as well as a Yii javascript file called jquery.yiiactiveform.js
            2. In your controller, in create or update, after you load the model, but before you load it from POST, call this
              if(Yii::app()->getRequest()->getIsAjaxRequest()) {
              echo CActiveForm::validate( array( $model)); 
              Yii::app()->end(); 
              } 
              Which is sligtly different than how Gii generates it, but no big diff. CActiveForm::validate() can take an array of models, which is not clear the way Gii does it.
            3. Also make sure that your model has at lease one validation rule for the insert or update scenario. After you tab out of a changed field, Yii sends a standard AJAX POST to the server, and gets back a JSON response like this:
              {"Field_id":["Validation error a"],"Another_field_id":["Validation error B"]} 
              which yii then plugs into the error field below your field.
            4. When you use the $form->error() function, Yii adds a hidden div after your form element:
              <div id="Model_attributename_em_" class="errorMessage" style="display:none"></div>
              If that field has a validation error, then Yii sets the display to block, writes the validation error message to its innerHtml, and then you see the error. If it later validates, yii hides it again.
            5. Yii will also add class names to the parent container of the field that it's validating. In most cases, this is a <div class="row">. When a form field is valid, it adds "success" class to the div - which makes it green. When it's invalid, it adds "error" class, which makes it red. It also quickly adds a "validating" class, which does nothing, but you can supply it yourself and change the look of a field while it's validating.
            轉自:http://learnyii.blogspot.tw/2010/12/yii.html
            posted @ 2012-12-26 12:45 小果子 閱讀(537) | 評論 (0)編輯 收藏
                 摘要: 轉自:http://blog.csdn.net/yczz/article/details/5974235一、NoSQL簡述  CAP(Consistency,Availabiity,Partition tolerance)理論告訴我們,一個分布式系統不可能滿足一致性,可用性和分區容錯性這三個需求,最多只能同時滿足兩個。關系型數據庫通過把更新操作寫到事務型日志里實現了部分耐用性,...  閱讀全文
            posted @ 2012-12-24 17:19 小果子 閱讀(2113) | 評論 (0)編輯 收藏
            僅列出標題
            共58頁: First 5 6 7 8 9 10 11 12 13 Last 
            久久久免费观成人影院| 久久天天躁狠狠躁夜夜avapp| 久久精品国产亚洲精品2020| 欧美麻豆久久久久久中文| 亚洲Av无码国产情品久久| 久久男人中文字幕资源站| 伊人久久一区二区三区无码| 久久夜色精品国产亚洲| 亚洲色欲久久久综合网东京热 | 伊人色综合九久久天天蜜桃| 久久精品无码一区二区日韩AV | 精品无码久久久久久久久久| 久久久99精品一区二区| 色悠久久久久久久综合网| 伊色综合久久之综合久久| 亚洲国产精品无码久久久秋霞2| 精品国产VA久久久久久久冰| 奇米影视7777久久精品| 国产成人无码精品久久久久免费 | 精品久久久无码人妻中文字幕豆芽| 久久久久人妻一区精品色| 国产高清美女一级a毛片久久w | 伊人色综合久久天天人手人婷 | 狠狠色伊人久久精品综合网| 欧洲国产伦久久久久久久| 久久久久亚洲爆乳少妇无| 亚洲中文字幕无码久久2017| 粉嫩小泬无遮挡久久久久久| 亚洲综合久久夜AV | 香蕉久久永久视频| 成人妇女免费播放久久久| 欧美久久久久久精选9999| 久久91亚洲人成电影网站| 久久久久国产精品熟女影院| 四虎久久影院| 国产精品激情综合久久| 中文字幕成人精品久久不卡| 精品国产VA久久久久久久冰| 久久精品国产亚洲av水果派 | 日本加勒比久久精品| 久久国产乱子伦精品免费午夜|