Table of Contents
Scenarios of applying Redis Php in projects, project redisphp scenarios
Home Backend Development PHP Tutorial Scenarios for applying Redis Php in projects, project redisphp scenarios_PHP tutorial

Scenarios for applying Redis Php in projects, project redisphp scenarios_PHP tutorial

Jul 12, 2016 am 08:50 AM
php redis

Scenarios of applying Redis Php in projects, project redisphp scenarios

Foreword

In some cases, some students said why the string type cannot be used. The string type can be completely implemented

I suggest you read my column "Advanced Usage of Redis", which introduces the benefits of using hash type

Product dimension count

Count product likes, comments, appraisals, and views
Speaking of e-commerce, products are definitely inseparable, and the accompanying products have various counts (number of likes, number of comments, number of appraisals, number of views, etc.)
Redis commands are all atomic, and you can easily use INCR, DECR and other commands to count.

Use the Redis type: Hash. If you are not familiar with the redis data type, you can refer to
http://redis.io/topics/data-types-intro

Define a key product: for product, and define a hashkey for each value, such as like number like_num

$redis->hSet('product:123', 'like_num ', 5); // 添加 id为123的商品 like_num 为5
 
$redis->hIncrBy('product:123', 'like_num ', 1); // 添加 id为123的商品like_num +1

$redis->hGetAll('product:123'); // 获取id为123的商品相关信息
                  array('like_num '=> 1)

Copy after login

User dimension count

Count the number of user updates, number of followers, number of fans, number of liked products, number of posts, etc.
Both user dimension counting and product dimension counting use Hash. Define a key for User as user:
Define a hashkey for each value, such as the number of followers follow

$redis->hSet('user:100000', 'follow ', 5); // 添加uid为10000的用户follow 为5
 
$redis->hIncrBy('user:100000', 'follow ', 1); // 更新uid为10000的用户follow +1

$redis->hGetAll('user:100000'); // 获取uid为10000的用户
                  array('like_num '=> 1)

Copy after login

                                                       
Storing social relationships

For example, the user’s friends/fans/follows can be stored in a sorted set, and the score can be timestamp

The default collection is sorted by increasing score
To find mutual friends between two people, you may only need to use the intersection command

$redis->zAdd('user:1000:follow', 1463557212, '1001'); 

                #uid为1000用户关注uid为1001 , score值设定时间戳1463557212

$redis->zAdd('user:1000:follow', 1463557333, '1002'); 

$redis->zAdd('user:2000:follow', 1463577568, '1001'); 

$redis->zAdd('user:2000:follow', 1463896964, '1003');
 
                #uid为2000用户关注1001和1003用户 , score值设定时间戳

$redis->zInter('com_fllow:1000:2000', array('user:1000:follow', 'user:2000:follow')); 

    #对集合'user:1000:follow'和'user:2000:follow'取交集'com_fllow:1000:2000'
    #获得共同关注的uid 

$redis->zRange('com_fllow:1000:2000',0,-1); // 获取全部集合元素
    #array('10001','10002')

Copy after login

Used as cache instead of memcached

Apply to product list, comment list, @tip list

Compared with memcached’s simple key-value storage, redis has numerous data structures (list, set, sorted set, hash,

etc)

It can cache various business data more conveniently, and its performance is no less than memcached.

NOTE: RPUSH pagewviews.user: EXPIRE pagewviews.user: 60 //Pay attention to update timeout

Anti-spam system

Spam control for application system comments, product publishing, and forum postings

As an e-commerce website, it is inevitable to be attacked by various spam (spam comments, posting spam products, advertisements, brushing the ranking of your own products, etc.)

Develop a series of anti-spam rules for these spams, some of which can use redis for real-time analysis

For example: no more than 2 comments in 1 minute, less than 5 comments in 5 minutes, etc. (More mechanisms/rules need to be combined with drools)

Regular sorted set records user operations in the last day
(Why not record everything? To save memory, all operations will be recorded in the log, and Hadoop will be used for more comprehensive analysis and statistics in the future)

#获取5秒内操作记录
$res = $redis->zRangeByScore('user:1000:comment', time() - 5, time());
#判断5秒内不能评论
if (!$res) {
  $redis->zAdd('user:1000:comment', time(), '评论内容');
} else {
  echo '5秒之内不能评论';
}

#5秒内评论不得超过2次
if($redis->zRangeByScore('user:1000:comment',time()-5 ,time())==1)
echo '5秒之内不能评论2次';

#5秒内评论不得少于2次

if(count($redis->zRangeByScore('user:1000:comment',time()-5 ,time()))<2)
echo '5秒之内不能评论2次';


 

Copy after login

User Timeline/Feeds

Apply to people, topics, brands and columns you follow

Redis is mainly used as cache here

$redis->zAdd('user:2000:feed:topic', time(), '13');
//score 为timestamp uid为2000的用户关注tid为13的topic

$redis->expire('user:2000:feed:topic',24*60*60);
#关注有效期为24小时
# ttl 30天之内按秒数计算 30天之外以timestamp为准

Copy after login

Latest List & Ranking

Used to record business scenarios such as the latest list or ranking of products that the user just liked

The latest list of products-sorted set structure presentation

    $redis->zAdd('user:1000:product:like', time(), '3002');
    $redis->zAdd('user:1000:product:like', time(), '3001');
    $redis->zAdd('user:1000:product:like', time(), '3004');
    $redis->zAdd('user:1000:product:like', time(), '3003');
    
    $redis->zRange('user:1000:product:like', 0, -1,true); 
    #默认喜欢时间升序序排列
    #
      Array(
        [3002] => 1463565179
        [3001] => 1463565189
        [3004] => 1463565199
        [3003] => 1463565209
      )
    
    $redis->zRevRange('user:1000:product:like', 0, -1,true); 
    #以喜欢时间降序排列
    #
      Array
      (
        [3003] => 1463565424
        [3004] => 1463565414
        [3001] => 1463565404
        [3002] => 1463565394
      )
    

Copy after login
Ranking list-list data structure presentation

    $redis->lPush('user:1000:product:like', '3002');
    $redis->lPush('user:1000:product:like', '3001');
    $redis->lPush('user:1000:product:like', '3004');
    $redis->lPush('user:1000:product:like', '3003');
    
    $redis->lRange('user:1000:product:like', 0, -1);
    
    Array
    (
      [0] => 3003
      [1] => 3004
      [2] => 3001
      [3] => 3002
    )
Copy after login

Message notification

Use Hash structure to count message notification business scenarios


$redis->hSet('user:1000:message:notice', 'system', 1);
#设置1条未读系统消息

$redis->hIncrBy('user:1000:message:notice', 'system', 1);
#未读系统消息+1

$redis->hSet('user:1000:message:notice', 'comment', 1);
#设置1条未读评论

$redis->hIncrBy('user:1000:message:notice', 'comment', 1);
#未读评论+1

$redis->hGetAll('user:1000:message:notice');
#查看所有消息通知数量

Array
(
  [system] => 2
  [comment] => 2
)



Copy after login

Use Redis as a message queue

Using Redis’ List data structure to implement distributed message queue

http://www.bkjia.com/PHPjc/1133110.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1133110.htmlTechArticleScenarios for applying Redis Php in the project, project redisphp scenario Preface In some cases, some students said why string cannot be used Type, string type can be implemented completely. I suggest you take a look...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles