Php_redis self-setting class ____php

Source: Internet
Author: User
Tags auth redis time 0 delete cache

Recently in doing a voting system, the original company's system is too redundant, high concurrency, no nginx, no redis, all rely on SQL update, lock the card before ...

Originally also just scattered use of redis, this time directly to encapsulate him into a class bar, convenient to use later.

First share the basic Redis tools:


1. Interface Management Tools

2.window_redis (You can play yourself under Windows)

3.Redis Official website (website does not understand the command, the main master its parameters and return value, very key)

4.Redis command (for future reference)

5.Redis related gadgets: Redis-load, Redis-stat

Redis-load and Redis-stat are two gadgets written by Redis author Antirez, where Redis-load is a stress test tool Redis is Redis-stat's status monitoring tool related code see: Redis Github.com/antirez/redis-tools

Redis Data Summary topic

Http://blog.nosqlfan.com/html/3537.html

This article lists some Redis in PHP commonly used operations, may not be too complete, or some to optimize the place, later will improve, but also to share to everyone.

<?php/** * Class Redisvote Redis operation class, integrates Redis common operation method * @time, 2016.03.07 * * class redisvote{public $redis _obj = n Ull;//redis the static variable public function __construct ($host = ' 127.0.0.1 ', $port =6379, $auth = "password") {$this->r
		    Edis_obj = new Redis ();
		    $this->redis_obj->connect ($host, $port);
		    $this->redis_obj->auth ($auth);
	return $this->redis_obj; }/*------------------------------------start 1.string structure----------------------------------------------------*/* * * Add, Set value build a String * @param string $key Key Name * @param string $value Set value * @param int $timeOut time 0 means no expiration time *  return true "always returns True" */Public function set ($key, $value, $timeOut =0) {$setRes = $this->redis_obj->set ($key,
		$value);
		if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $setRes; /** * Check, get the value of a key, there is no return false * @param $key, the key value * @return bool|string, the query successfully returned the information, failed to return false */Public function Get ($key) {$setRes = $this->redis_obj->get ($key);//does not exist returns False if ($setRes = = ' false ') {return false;
	return $setRes; }/*------------------------------------1.end string Structure----------------------------------------------------/*/*-- ----------------------------------2.START list Structure----------------------------------------------------//** * increased, Build a list (advanced, like stacks) * @param string $key Key Name * @param string $value value * @param $timeOut |num expires/public funct
		Ion Lpush ($key, $value, $timeOut =0) {//echo "$key-$value \ n";
		$re = $this->redis_obj->lpush ($key, $value);
		if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $re; /** * increase, build a list (advanced first, similar queue) * @param string $key Key Name * @param string $value value * @param $timeOut |num Expiration *
		/Public Function Rpush ($key, $value, $timeOut =0) {//echo "$key-$value \ n";
		$re = $this->redis_obj->rpush ($key, $value); if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $re; /** * Check, get all the list data (from beginning to end) * @param string $key key name * @param int $head start * @param int $tail End * * Publ
	IC function Lranges ($key, $head, $tail) {return $this->redis_obj->lrange ($key, $head, $tail); }/*------------------------------------2.end list structure----------------------------------------------------/*---- --------------------------------3.start Set Structure----------------------------------------------------//** * increase, build a set (Unordered collection) * @param string $key set y name * @param string|array $value value * @param int $timeOut time 0 means no expiration * @return *
		/Public Function Sadd ($key, $value, $timeOut = 0) {$re = $this->redis_obj->sadd ($key, $value);
		if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $re; /** * Check, take the set corresponding element * @param string $key set name/Public function smembers ($key) {$re = $this->redis_obj->
		Exists ($key);/exists returns 1, does not exist returns 0 if (! $re) return false; return $this->redis_obj->smemBers ($key); }/*------------------------------------3.end SET structure----------------------------------------------------/*----- -------------------------------4.start Sort Set Structure----------------------------------------------------/* * Add, change, build A collection (ordered set) that supports batch writes, updates * @param string $key collection name * @param array $score _value key is Scoll, value is the values of that right * @return int insert operation successfully returns INSERT Quantity ", update operation returns 0"/Public function Zadd ($key, $score _value, $timeOut =0) {if (!is_array ($score _value)) ret
		Urn false; $a = 0;//Stores the number of inserts foreach ($score _value as $score => $value) {$re = $this->redis_obj->zadd ($key, $score, $value);
			When modified, it is possible to modify, but not return the updated quantity $re && $a +=1;
		if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $a; /** * Check, ordered set query, can be ascending descending, default starting from the first, query a data * @param $key, the query's key value * @param $min, starting from article $min * @param $max, query the number of bars * @pa Ram $order, ASC for ascending sort, desc for descending sort * @return Array|bool If successful, returns query information if the failure returns false */Public function Zrange ($Key, $min = 0, $num = 1, $order = ' desc ') {$re = $this->redis_obj->exists ($key);/exists to return 1, does not exist returns 0 if (! $re) return F
		alse;//does not exist a key value if (' desc ' = = Strtolower ($order)) {$re = $this->redis_obj->zrevrange ($key, $min, $min + $num-1);
		}else{$re = $this->redis_obj->zrange ($key, $min, $min + $num-1);
	if (! $re) return false;//The range value of the query is null return $re; /** * Returns to the collection key, member's rank * @param $key, the key value * @param $member, the scroll value * @param $type, is the sequential lookup or the reverse order * @return Boo
		L, the key value does not exist returns false, exists returns its rank subscript/Public Function Zrank ($key, $member, $type = ' desc ') {$type = Strtolower (Trim ($type));
			if ($type = = ' desc ') {$re = $this->redis_obj->zrevrank ($key, $member);//The ordered set members are sorted in descending order of score values (from large to small), returning their rank}else{ $re = $this->redis_obj->zrank ($key, $member), or in which ordered set members are incremented by score value (small to large), returning their rank} if (!is_numeric ($re)) return F
	alse;//There is no key value return $re;
	 /** * Returns all elements of score >= star and score <= end in Zset named key * @param $key * @param $member * @param $star,* @param $end, * @return array/Public function Zrangbyscore ($key, $star, $end) {return $this->redis_obj->zra
	Ngebyscore ($key, $star, $end); /** * Returns the score * @param of element member in Zset named Key $key * @param $member * @return String, returns the member value of the query * * functio
	N Zscore ($key, $member) {return $this->redis_obj->zscore ($key, $member); }/*------------------------------------4.end Sort Set Structure----------------------------------------------------/*/*- -----------------------------------5.hash Structure----------------------------------------------------* * */** * increased, Inserts data into the cache in JSON format, hash type * @param $redis _key |array, $redis table name of the _key[' key ' database, $redis _key[' field '], subscript key * @param $token, The token of the activity, used to differentiate between the identity * @param $id, the ID of the activity that distinguishes the identity * @param $data |array, the data to be inserted, * @param $timeOut, expiration time, defaults to 0 * @return $ Number insert successfully returned 1 ", update operation returned 0"/Public function Hset_json ($redis _key, $token, $id, $data, $timeOut = 0) {$redis _table_name =			$redis _key[' key ']. $token; The name of the key $redis _kEy_name = $redis _key[' field ']. ': $id;							The name of the field that represents the first few activities $redis _info = Json_encode ($data); field data value, stored as JSON $re = $this->redis_obj-> hset ($redis _table_name, $redis _key_name, $redis _info);
	Cache if ($timeOut > 0) $this->redis_obj->expire ($redis _table_name, $timeOut);//Set Expiration time return $re; /** * Check, JSON-stored hash cache, a value is returned, no value is queried the database and stored in the cache * @param $redis, $redis [' key '], $redis [' field '] is hash table name and key value * @param $ token, the $token for the public number * @param $token, $id for the active ID * @return Bool|array, successfully return the information to be queried, failed or does not exist return FALSE * * * *-function Hget_js On ($redis _key, $token, $id) {$re = $this->redis_obj->hexists ($redis _key[' key '). ': $token, $redis _key[' field '] . ': '. $id); Returns whether the field of this hash type exists in the cache if ($re) {$info = $this->redis_obj->hget ($redis _key[' key '). '. $token, $
			redis_key[' field ']. ': '. $id);
		$info = Json_decode ($info, true);
		}else{$info = false;
	return $info; /** * increase, normal logic insert hash data type value * @param $key, Key name * @param $data |array one-dimensional array, the data to be stored * @param $timeOut |num expiration * @return $number return OK "update and insert operation return OK" * * * Public Function Hmset ($key, $data, $time
		out=0) {$re = $this->redis_obj-> hmset ($key, $data);
		if ($timeOut > 0) $this->redis_obj->expire ($key, $timeOut);
	return $re; /** * Check, the normal get value * @param $key, indicating that the hash subscript value * @return Array.
		The array information for the query is returned successfully, no information returns false * */Public Function Hval ($key) {$re = $this->redis_obj->exists ($key);/exists returns 1, does not exist return 0
		if (! $re) return false;
		$vals = $this->redis_obj-> hvals ($key);
		$keys = $this->redis_obj-> hkeys ($key);
		$re = Array_combine ($keys, $vals);
		foreach ($re as $k => $v) {if!is_null (Json_decode ($v)) {$re [$k] = Json_decode ($v, true);//true to return JSON to an array}
	return $re; }/** * * @param $key * @param $filed * @return bool|string/Public Function Hget ($key, $filed) {$re = $th
		Is->redis_obj->hget ($key, $filed);
		if (! $re) {return false;
	return $re; }

	/*------------------------------------END Hash Structure----------------------------------------------------*/*---------------------------------- --Other structure----------------------------------------------------//** * Set self-increase, self-subtraction function * @param $key, the key value to be changed * @param int $nu M, the magnitude of the change, default is 1 * @param string $member, type is zset or hash, need to enter member or filed field * @param string $type, type, default for ordinary increase or decrease, and: Zset, Hash * @return Bool|int successfully returns the scroll integer, Failure returns false * */Public Function incre ($key, $num = 1, $member = ', $type = ') {$
		num = Intval ($num); Switch (Strtolower (Trim ($type)) {case "Zset": $re = $this->redis_obj->zincrby ($key, $num, $member);//Growth Right value B
			Reak;
			Case "Hash": $re = $this->redis_obj->hincrby ($key, $member, $num);//increase value in HashMap break; Default:if ($num > 0) {$re = $this->redis_obj->incrby ($key, $num);//default growth}else{$re = $this->
		Redis_obj->decrby ($key,-$num);//default growth} break;
		if ($re) return $re;
	return false; /** * Clear Cache * @param int $typeThe default is 0, clear the current database, 1 to clear all cache/function flush ($type = 0) {if ($type) {$this->redis_obj->flushall ();//Clear All databases}e lse{$this->redis_obj->flushdb ()//Purge Current database}/** * Verify that a key value exists * @param $keys, the key value * @param string $ty PE, type, default to General * @param string $field. For hash type, enter $field * @return bool/Public function exists ($keys, $type = ', $field = ') {switch (Trim ($typ
			e)) {case ' hash ': $re = $this->redis_obj->hexists ($keys, $field);//There is return 1, no return 0 break;
				Default: $re = $this->redis_obj->exists ($keys);
		Break
	return $re; /** * Delete Cache * @param string|array $key, key value * @param $type, type, default to general, and Hash,zset * @param string $field,hash=> table The $field value,set=> indicates that the value,zset=> represents the value, and the list type is special for temporary non-@return int | , returns the number of deletes/public function delete ($key, $type, $field = ') {switch (Strtolower ($type)) {case ' hash ': $re
			= $this->redis_obj->hdel ($key, $field);//return delete number break; Case ' Set ': $re= $this->redis_obj->srem ($key, $field);//return delete number break;
			Case ' Zset ': $re = $this->redis_obj->zdelete ($key, $field);//return delete number of break;
		Default: $re = $this->redis_obj->del ($key);//return delete number of break;
	return $re;   }//Logging public Function Logger ($log _content, $position = ' user ') {$max _size = 1000000; Declare the maximum size of the log 1000K $log _dir = './log ';//log Store root if (!file_exists ($log _dir)) mkdir ($log _dir,0777); If the folder does not exist, create if ($  Position = = ' user ' {$log _filename = ' {$log _dir}/user_redis_log.txt ';  Log name}else{$log _filename = "{$log _dir}/wap_redis_log.txt"; Log name}//If the file exists and is larger than the specified maximum size, delete the IF (file_exists ($log _filename) && (ABS ($log _filename) > $max _
		Size)) {unlink ($log _filename); //write to the log, add the time before the content, followed by a newline, and write to File_put_contents ($log _filename, date (' Y-m-d_h:i:s ') in append mode. ". $log _content."
	\ n ", file_append);
	function __destruct () {$this->redis_obj->close (); }}?>

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.