PHP Cloud storage Redis Application scenarios and Redis to achieve the ranking function

Source: Internet
Author: User
Tags auth hash redis port number redis server value store

CRS can be used as caching, in session caching, full-page caching, improving database query performance, and other scenarios have a significant advantage; CRS can also be used as a key-value store with high reliability of data that can generate Lengbei and log back through the logs on a daily basis. In the rankings, counter applications, real-time systems, after reading that burning needs to accurately set the expiration time of the application, anti-spam systems and other scenarios can greatly improve efficiency.

Cloud storage Redis Usage scenarios, application scenarios, product features and architecture Introduction:

Working with scenes


Application Scenarios


Product Features


Architecture Introduction


PHP Pre-run Prerequisites:

Using client Phpredis, download and reference address: Https://github.com/phpredis/phpredis

"Sample Code"

<?php
/** the following parameters fill in your Redis instance intranet IP, port number, instance ID and password.
$host = "192.168.0.2";
$port = 6379;
$instanceid = "c532952f-55dc-4c22-a941-63057e560788";
$pwd = "1234567q";

$redis = new Redis ();
Connect Redis
if ($redis->connect ($host, $port) = = False) {
Die ($redis->getlasterror ());
}
The right to authentication
if ($redis->auth ($instanceid. ":" . $PWD) = = False) {
Die ($redis->getlasterror ());
}

/** next can be happy to start Operation Redis instance, can refer to: Https://github.com/phpredis/phpredis * *

Set key
if ($redis->set ("Redis", "piaoyi.org") = = False) {
Die ($redis->getlasterror ());
}
echo "Set key Redis OK, value is:piaoyi.org\n";

Get key
$value = $redis->get ("Redis");
echo "Get key Redis is:". $value. " \ n ";
?>

A small example of using Redis to achieve the score list:

Points list Category
Class Ranks {
Const PREFIX = ' rank: ';
protected $redis = null;
Public function __construct (Redis $redis) {
$this->redis = $redis;
}
Public Function Addscores ($member, $scores, $date = "") {
if ($date = = "") $key = self::P refix. Date (' Ymd ');
else $key = self::P refix. $date;
return $this->redis->zincrby ($key, $scores, $member);
}
function Getonedayrankings ($date, $start, $stop) {
$key = self::P refix. $date;
return $this->redis->zrevrange ($key, $start, $stop, true);
}
protected function Getmultidaysrankings ($dates, $outKey, $start, $stop) {
$keys = Array_map (function ($date) {
Return self::P refix. $date;
}, $dates);
$weights = Array_fill (0, Count ($keys), 1);
$this->redis->zunion ($outKey, $keys, $weights);//A collection, the same key will sum up
return $this->redis->zrevrange ($outKey, $start, $stop, true);
}
Public Function GetYesterdayTop10 () {
$date = Date (' Ymd ', Strtotime ('-1 day '));
return $this->getonedayrankings ($date, 0, 9);
}
public static function Getcurrentmonthdates () {
$BeginDate =date (' y-m-01 ', Strtotime (date ("y-m-d")); 1th Day of Current month
$curDate = (int) date (' d ', strtotime (date ("y-m-d"));
$dates = Array ();
for ($day = 0; $day < $curDate; $day + +) {
$dates [] = date (' Ymd ', Strtotime ("$BeginDate + $day Day"));
}
return $dates;
}
Public Function GetCurrentMonthTop10 () {
$dates = Self::getcurrentmonthdates ();
return $this->getmultidaysrankings ($dates, ' Rank:current_month ', 0, 9);
}
}

The above class uses:

Instantiation of
$rank = new ranks ($redis);

$rank->addscores (1, 3, "20151106");
$rank->addscores (2, 2, "20151106");
$rank->addscores (3, 1, "20151106");

$rank->addscores (1, 1, "20151107");
$rank->addscores (2, 3, "20151107");
$rank->addscores (3, 2, "20151107");

Print_r ($rank->getyesterdaytop10 ());
Print_r ($rank->getcurrentmonthtop10 ());
Print_r ($rank->getonedayrankings ("20151106", 0,-1));
Print_r ($rank->getonedayrankings ("20151107", 0,-1));


Some of the supported methods:

Connection

Connect, open-connect to a server
Pconnect, Popen-connect to a server (persistent)
Auth-authenticate to the server
Select-change the selected database for the current connection
Close-close the connection
Setoption-set Client option
Getoption-get Client option
Ping-ping the server
Echo-echo the given string

Keys and Strings

Strings (String)

Append-append a value to a key
Bitcount-count set bits in a string
Bitop-perform bitwise operations between strings
DECR, decrby-decrement the value of a key
Get-get the value of a key
Getbit-returns the bit value at offset in the string value stored at key
Getrange-get a substring of the string stored at a key
Getset-set the string value of a key and return it old value
INCR, incrby-increment the value of a key
Incrbyfloat-increment the float value of a key by the given amount
Mget, Getmultiple-get the values of all the given keys
Mset, msetnx-set multiple keys to multiple values
Set-set the string value of a key
Setbit-sets or clears the bit at offset on the string value stored at key
Setex, psetex-set the value and expiration of a key
Setnx-set the value of a key, only if the key does not exist
Setrange-overwrite part of a string on key starting at the specified offset
Strlen-get the length of the value stored in a key

Keys (keys)

Del, delete-delete a key
Dump-return a serialized version of the value stored at the specified key.
Exists-determine if a key exists
Expire, settimeout, pexpire-set a key ' s time to live in seconds
Expireat, pexpireat-set the expiration for a key as a UNIX timestamp
Keys, getkeys-find All keys matching the given pattern
Scan-scan for keys in the keyspace (Redis >= 2.8.0)
migrate-atomically transfer a key from a Redis instance to another one
Move-move a key to another database
Object-inspect the internals of Redis objects
Persist-remove the expiration from a key
Randomkey-return a random key from the Keyspace
Rename, Renamekey-rename a key
Renamenx-rename a key, only if the new key does not exist
Type-determine the type stored at key
Sort-sort the elements in a list, set or sorted set
TTL, pttl-get the time to live for a key
Restore-create a key using the provided serialized value, previously obtained with dump.


Hashes (hash table)

Hdel-delete one or more hash fields
Hexists-determine If a hash field exists
Hget-get the value of a hash field
Hgetall-get all the fields and values in a hash
Hincrby-increment the integer value of a hash field by the given number
Hincrbyfloat-increment the float value of a hash field by the given amount
Hkeys-get all the fields in a hash
Hlen-get the number of fields in a hash
Hmget-get the values of all the given hash fields
Hmset-set multiple hash fields to multiple values
Hset-set the string value of a hash field
Hsetnx-set the value of a hash field, only if the field does not exist
Hvals-get all of the values in a hash
Hscan-scan a hash key for members


Lists (list)

Blpop, Brpop-remove and get the first/last element in a list
Brpoplpush-pop a value from a list, push it to another list and return it
Lindex, lget-get a element from a list by its index
Linsert-insert an element before or after another element in a list
Llen, Lsize-get the length/size of a list
Lpop-remove and get the The
Lpush-prepend one or multiple values to a list
Lpushx-prepend a value to a list, only if the list exists
Lrange, lgetrange-get a range of elements from a list
Lrem, lremove-remove elements from a list
Lset-set the value of a element in a list by its index
LTrim, Listtrim-trim a list to the specified range
Rpop-remove and get the last element in a list
Rpoplpush-remove the last element in a list, append it to another list and return it (Redis >= 1.1)
Rpush-append one or multiple values to a list
Rpushx-append a value to a list, only if the list exists


Sets (Collection)

Sadd-add one or more members to a set
SCard, ssize-get the number of members in a set
Sdiff-subtract Multiple Sets
Sdiffstore-subtract multiple sets and store the resulting set in a key
Sinter-intersect Multiple Sets
Sinterstore-intersect multiple sets and store the resulting set in a key
Sismember, Scontains-determine If a given value is a of a set
Smembers, Sgetmembers-get all of the members in a set
Smove-move a member from one set to another
Spop-remove and return a random member from a set
Srandmember-get one or multiple random members from a set
Srem, Sremove-remove One or more members of a set
Sunion-add Multiple Sets
Sunionstore-add multiple sets and store the resulting set in a key
Sscan-scan a set for members


Sorted sets (ordered set)

Zadd-add one or more members to a sorted the set or update its score if it already exists
Zcard, zsize-get the number of members in a sorted set
Zcount-count the members of a sorted set with scores within the given values
Zincrby-increment the score of a member in a sorted set
Zinter-intersect multiple sorted sets and store the resulting sorted set in a new key
Zrange-return a range of members in a sorted set, by index
Zrangebyscore, Zrevrangebyscore-return a range of members in a sorted set, by score
Zrangebylex-return a lexigraphical range from members that share the same score
Zrank, zrevrank-determine the index of a in a sorted set
Zrem, Zdelete-remove One or more members from a sorted set
Zremrangebyrank, Zdeleterangebyrank-remove all members in a sorted set within the given indexes
Zremrangebyscore, Zdeleterangebyscore-remove all members in a sorted set within the given scores
Zrevrange-return a range of members in a sorted set, by index, with scores ordered
Zscore-get the score associated with the given member in a sorted set
Zunion-add multiple sorted sets and store the resulting sorted set in a new key
Zscan-scan a sorted set for members


Transactions (transaction)

Multi, exec, Discard-enter and exit transactional mode
Watch, unwatch-watches a key for modifications by another client.


Servers (server-side commands)

bgrewriteaof-asynchronously rewrite the append-only file
bgsave-asynchronously Save the DataSet to disk (in background)
Config-get or Set the Redis server configuration parameters
Dbsize-return the number of keys in selected database
Flushall-remove all keys from all databases
Flushdb-remove all keys to the current database
Info-get information and statistics about the server
Lastsave-get the timestamp of the last disk save
Resetstat-reset the stats returned by info method.
save-synchronously Save the DataSet to disk (wait to complete)
Slaveof-make the server A slave of another instance, or promote it to master
Time-return the current server time
Slowlog-access the Redis slowlog entries




using Redis to achieve the ranking function



The list function is a very common requirement. It is a good and quick choice to use the features of ordered sets in Redis to achieve the rankings.

The general rankings are effective, such as "User standings." If the results are not always ranked according to the overall list, it is possible that the top is always a few old users, for new users, it is really frustrating.

First of all, to a "Today's standings" bar, the collation is today users add more points from more to less.

Then the user increases the integral, all operates the record day integral increment order collection.
Assuming today is April 01, 2015, the user with a UID of 1 adds 5 points for an operation.
The Redis command is as follows:

Zincrby rank:20150401 5 1

Suppose there are several other users who also add points:

Zincrby rank:20150401 1 2
Zincrby rank:20150401 10 3

Look at the data in the ordered set rank:20150401 now (withscores parameters can be shipped with score of the element):

Zrange rank:20150401 0-1 Withscores

1) "2"
2) "1"
3) "1"
4) "5"
5) "3"
6) "10"

To obtain TOP10 from high to low scores:

Zrevrange rank:20150401 0 9 Withscores

1) "3"
2) "10"
3) "1"
4) "5"
5) "2"
6) "1"

Because there are only three elements, the data is queried.

If you record that day's score list, then the other list is simple.
Like "Yesterday's standings":

Zrevrange rank:20150331 0 9 Withscores

Achieve the "Last week's standings" by using the combined set to realize the sum of many days ' points:

Zunionstore Rank:last_week 7 rank:20150323 rank:20150324 rank:20150325 rank:20150326 rank:20150327 rank:20150328 Rank : 20150329 WEIGHTS 1 1 1 1 1 1 1

This merges the 7-day integration record into an ordered set of Rank:last_week. Weight factor WEIGHTS If not, the default is 1. In order not to hide the details, deliberately write.
So the message for the TOP10 last week's standings is:

Zrevrange Rank:last_week 0 9 Withscores

"Monthly List", "Quarterly", "annual list" and so on and so on.

Here is a simple implementation of a PHP version. Using Redis relies on the PHP extension Phpredis, the code also relies on the Carbon library for processing time. The amount of code is small, so you don't have to comment.

<?php

namespace Blog\redis;

Use \redis;
Use Carbon\carbon;


Class Ranks {

Const PREFIX = ' rank: ';

protected $redis = null;


Public function __construct (Redis $redis) {
$this->redis = $redis;
}


Public Function Addscores ($member, $scores) {
$key = self::P refix. Date (' Ymd ');
return $this->redis->zincrby ($key, $scores, $member);
}


protected function Getonedayrankings ($date, $start, $stop) {
$key = self::P refix. $date;
return $this->redis->zrevrange ($key, $start, $stop, true);
}


protected function Getmultidaysrankings ($dates, $outKey, $start, $stop) {
$keys = Array_map (function ($date) {
Return self::P refix. $date;
}, $dates);

$weights = Array_fill (0, Count ($keys), 1);
$this->redis->zunion ($outKey, $keys, $weights);
return $this->redis->zrevrange ($outKey, $start, $stop, true);
}


Public Function GetYesterdayTop10 () {
$date = Carbon::now ()->subdays (1)->format (' Ymd ');
return $this->getonedayrankings ($date, 0, 9);
}


public static function Getcurrentmonthdates () {
$dt = Carbon::now ();
$days = $dt->daysinmonth;

$dates = Array ();
for ($day = 1; $day <= $days; $day + +) {
$dt->day = $day;
$dates [] = $dt->format (' Ymd ');
}
return $dates;
}


Public Function GetCurrentMonthTop10 () {
$dates = Self::getcurrentmonthdates ();
return $this->getmultidaysrankings ($dates, ' Rank:current_month ', 0, 9);
}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.