zoukankan      html  css  js  c++  java
  • php +redis实现简单的消息队列

    Redis


    Redis是一个开源,高级的键值存储和一个适用的解决方案,用于构建高性能,可扩展的Web应用程序。

    Redis有三个主要特点,使它优越于其它键值数据存储系统 -

    • Redis将其数据库完全保存在内存中,仅使用磁盘进行持久化。
    • 与其它键值数据存储相比,Redis有一组相对丰富的数据类型。
    • Redis可以将数据复制到任意数量的从机中。

    Redis支持的数据类型有 Stirng(字符串), List(列表), Hash(字典), Set(集合), Sorted Set(有序集合);

    redis 队列


           redis 提供了两种方式来作消息队列。一个是生产者消费模式,另外是发布订阅模式。前者会让一个或者多个客户端监听消息队列,消费者消费;后者是一个或者多个客户端订阅频道,只要发布者发布消息,所以订阅者都能收到消息,订阅者都是平等的。

          生产者消费模式

          1、定时任务入列rpush

           2、定时任务出列lpop

          入列文件pre.php:

    <?php
    
    $redis=new Redis();
    $redis->connect('127.0.0.1','6379');
    $password='fenglove';
    $redis->auth($password);
    $arr=array('h','e','l','l','o','w','o','r','l','d');
    foreach($arr as $k=>$v){
    
     $redis->rpush('mylist',$v);
    
    }

        出列文件index.php:

    <?php
     $redis=new Redis();
     $redis->connect('127.0.0.1',6379);
     $password='fenglove';
     $redis->auth($password);
    //list类型出队操作
    $value=$redis->lpop('mylist');
    if($value){
     echo '出队的值'.$value;
    
    }else{
     echo "出队完成";
    }

    开启定时任务:

    在/etc/中

    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    HOME=/
    
    # For details see man 4 crontabs
    
    # Example of job definition:
    # .---------------- minute (0 - 59)
    # |  .------------- hour (0 - 23)
    # |  |  .---------- day of month (1 - 31)
    # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
    # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    # |  |  |  |  |
    # *  *  *  *  * user-name command to be executed
    1 * * * * root /bin/netstat -lntp
    * * * * * root  /usr/local/php/bin/php  /root/test.php >> /root/test.log
    * * * * * root /usr/local/php/bin/php  /root/phptest/index.php
    */10 * * * * root /usr/local/php/bin/php  /root/phptest/pre.php

    结果:

     1 127.0.0.1:6379> lrange mylist 0 -1
     2  1) "h"
     3  2) "e"
     4  3) "l"
     5  4) "l"
     6  5) "o"
     7  6) "w"
     8  7) "o"
     9  8) "r"
    10  9) "l"
    11 10) "d"
    12 127.0.0.1:6379> lrange mylist 0 -1
    13 1) "e"
    14 2) "l"
    15 3) "l"
    16 4) "o"
    17 5) "w"
    18 6) "o"
    19 7) "r"
    20 8) "l"
    21 9) "d"
  • 相关阅读:
    [LeetCode]题解(python):089-Gray Code
    [LeetCode]题解(python):088-Merge Sorted Array
    [LeetCode]题解(python):086-Partition List
    [LeetCode]题解(python):083-Remove Duplicates from Sorted List
    [LeetCode]题解(python):082-Remove Duplicates from Sorted List II
    [LeetCode]题解(python):081-Search in Rotated Sorted Array II
    [LeetCode]题解(python):080-Remove Duplicates from Sorted Array II
    [LeetCode]题解(python):079-Word Search
    [LeetCode]题解(python):078-Subsets
    软件开发冲刺5
  • 原文地址:https://www.cnblogs.com/jjffeng-/p/7873418.html
Copyright © 2011-2022 走看看