Use of Yum installation and use of Redis method of detailed _redis

Source: Internet
Author: User
Tags auth cas crc32 memcached redis server port install redis redis server

Introduced

Redis is a key-value storage system. Like memcached, it supports a relatively larger number of stored value types, including string (string), list (linked list), set (set), Zset (sorted set– ordered set), and hash (hash type). These data types support Push/pop, Add/remove and intersection-set and differential sets and richer operations, and these operations are atomic. On this basis, Redis supports a variety of different ways of ordering. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to the disk or writes the modification operation to the appended record file, and on this basis, it realizes the Master-slave (master-slave) synchronization.

This article mainly introduces the use of Yum to install Redis method, the following words do not say more, to see the detailed process.

First, execute the installation command

Second, the connection Redis

Note: If the following error is reported, it is not activated Redis

Could not connect to Redis at 127.0.0.1:6379:connection refused

Third, allow remote access Redis

To support remote access debugging, you need to annotate bind 127.0.0.1 in the configuration file, in addition to the need to open server port number 6379, but should be released from the production environment to avoid hacker attacks

Four, restart Redis

V. Test usage commands

Back: Hello World, proof of installation success





This article mainly introduces the CENTOS7 configuration Redis and boot, with a certain reference value, interested in the small partners can refer to.

Recently in doing homework need to use the Redis cache, because each restart the server needs to restart the Redis, it is annoying, so there is this blog, good, nonsense don't say much.

There are only two steps:

1. Set the redis.conf daemonize to Yes to ensure that the daemon is turned on.

2. Write the boot from boot script

The basic principle is:

When the system boots up, it will load the script below the/etc/init.d/, usually each script file will customize the implementation of the program, if you want to start the new program, just add a custom launcher script in the directory, and then set the appropriate rules.

If here we create a new Redis script under/etc/init.d/, it will be loaded to execute the script at boot up.

Vim/etc/init.d/redis

Add the content to the script:

# chkconfig:2345 #redis服务必须在运行级2, 3,4,5 is started or closed, the priority is 90, the priority of the shutdown is 10. # Description:start and Stop redis path=/usr/local/bin:/sbin:/usr/bin:/bin export PATH redisport=6379 #端口号, which is the default if you When the installation is not the default port number, you need to modify the location of the Exec=/usr/local/redis/bin/redis-server #redis-server startup script, and if you forget you can find the redis_cli=/by finding or Whereis
USR/REDISBIN/REDIS-CLI #redis-CLI The location of the client startup script, if you forget, you can find Pidfile=/run/redis.pid #这个也可以用find或whereis找到  
        conf= "/usr/local/redis/etc/redis.conf" #redis. conf configuration file location, if you forget you can use Find or whereis found auth= "1234" case "" in start) 
        If [f $PIDFILE] then echo $PIDFILE exists, process is already running or crashed. else echo "Starting Redis server ..." $EXEC $CONF fi if ["$?"  
    = "0"] then echo "Redis is running ..." FI; 
     STOP) if [! f $PIDFILE] then echo $PIDFILE exists, the process is not running.   Else pid=$ (cat $PIDFILE) echo "Stopping ..." $REDIS _cli-p $REDISPORT SHUTDOWN Sleep 2 While [-X $PIDFILE] do echo ' Waiting for Redis to Shutd  
    Own ... "Sleep 1 Redis stopped" FI;  
    restart|force-reload) ${0} stop ${0} start;;

 *) echo "Usage:/etc/init.d/redis {start|stop|restart|force-reload}" >&2 exit 1 Esac

Save exit after writing

To set executable permissions:

chmod 755 Redis

To start the test:

/etc/init.d/redis start

Startup success prompts you with the following information:

Starting Redis server ...
Redis is running ...

To use the REDIS-CLI test:

[Root@localhost ~]#/usr/local/redis/bin/redis-cli
127.0.0.1:6379> set foo bar
OK
127.0.0.1:6379> Get foo
"bar"
127.0.0.1:6379> exit

To set the power-on self boot:

Chkconfig Redis on

Shutdown reboot test:

Reboot

After the boot can be used REDIS-CLI test, or with Ps-ef | grep Redis See if Redis is running



Use Redis class to manipulate//instantiate Redis class $redis = new Redis ();
Select the specified Redis database connection, and the default port number is 6379 $redis->connect (' 127.0.0.1 ', 6379); $redis->auth (' mypasswords123sdfeak ');
Password verification//ordinary set/get operation $redis->set (' library ', ' Predis ');
$retval = $redis->get (' library '); Echo $retval; Displays the ' Predis '//setex set a storage aging $redis->setex (' str ', ten, ' Bar '); Indicates that the store is valid for 10 seconds//setnx/msetnx is equivalent to the add operation and does not overwrite existing values $redis->setnx (' foo ', 12); True $redis->setnx (' foo ', 34); False//getset operation, variant of Set, result returns the value before the replacement $redis->getset (' foo ', 56);//return to//INCRBY/INCR/DECRBY/DECR increment and decrement of value $redis- >INCR (' foo '); Foo $redis->incrby (' foo ', 2); Foo is//exists detect the existence of a value $redis->exists (' foo ');//true//del Delete $redis->del (' foo ');//true//type type detection, The string returns a string, the list returns the List,set table returns a hash $redis->type (' foo ');/does not exist, returns none $redis->set (' str ', ' Test ')
; $redis->type (' str '); String that returns string//append to the existing string $redis->append (' str ', ' _123′ '); Returns the cumulative string length 8, which enters str for the ' test_123′//setrange partial substitution operation $redis->setRange (' str ', 0, ' abc '); Returns 3, Parameter 2 is 0 o'clock equivalent to set operation $redis->setrange (' str ', 2, ' CD ');//return 4, End-of-file replaced from 2nd word, when ' str ' is the ' ABCD '//SUBSTR partial fetch operation $redis- >substr (' str ', 0,2); from No. 0, take to 2nd character, Total 3, return ' abc '//strlen get string length $redis->strlen (' str ');  Returns 4//setbit/getbit bits to store and get $redis->setbit (' binary ', 31, 1);    To save 1 in the 31st place, there may be a size end problem? But it doesn't matter, getbit should not have problems $redis->getbit (' binary ', 31);
Returns the 1//keys Fuzzy Lookup function, supports the * and number (matching one character) $redis->set (' foo1′,123);
$redis->set (' foo2′,456); $redis->keys (' foo* ');  Returns the array $redis->keys (' F?o? ') of Foo1 and Foo2; Ibid.//randomkey Returns a key $redis->randomkey () randomly; It is possible to return to ' foo1′ ' or ' foo2′ ' and any other Redis key//rename/renamenx rename the key, unlike Renamenx, which is not allowed to be changed to an existing key $redis->rename (' Str ', ' str2′); Changed the key originally named ' Str ' to ' Str2′//expire set Key-value's timeliness, TTL gets the remaining validity period, persist reset to permanent storage $redis->expire (' foo ', 1); Set a validity period of 1 seconds $redis->ttl (' foo '); Returns the expiration value of 1s $redis->expire (' foo ');

Cancels expire behavior//dbsize returns the total number of records Redis the current database $redis->dbsize (); /* Queue Operation * *//RPUSH/RPUSHX ordered list operation, the difference between inserting elements//lpush/lpushx and rpush/rpushx from the queue is inserted into the head of the queue, ditto, ' X ' meaning is to operate on the existing key only $redis->rpush (' foolist ', ' bar1′); Returns the length of a list of 1 $redis->lpush (' foolist ', ' bar0′ '); Returns the length of a list of 2 $redis->rpushx (' foolist ', ' bar2′ '); Returns 3,RPUSHX only adds to an existing queue, otherwise returns 0//llen returns the current list length $redis->llen (' foolist ');//3//lrange returns elements of an interval in the queue $redis->lrange (' Foolist ', 0, 1); The return array contains the NO. 0 to 1th total of 2 elements $redis->lrange (' foolist ', 0,-1);//Returns the No. 0 to the penultimate first, which is equivalent to returning all elements, noting that in redis many times a negative number is used, the same below//lindex Returns the list element at the specified ordinal position $redis->lindex (' foolist ', 1); Returns the value $redis->lset (' foolist ', 1, ' 123′) of the specified position in the Bar1′//lset modification queue;//Modify the element of position 1, return true//lrem delete the specified number of characters from the left queue $redis- >lrem (' Foolist ', 1, ' _ '); Delete Queue in the left (1) 1 characters ' _ ' (if any)//lpop/rpop similar stack structure to eject (and delete) the leftmost or the most right element $redis->lpop (' foolist '); ' bar0′ $redis->rpop (' foolist '); The ' Bar2′//ltrim queue is modified to retain several elements on the left, and the remainder is deleted $redis->ltrim (' foolist ', 0,1);
Keep the No. 0 to 1th elements on the left//rpoplpush pop out of the element from one queue and push to another queue $redis->rpush (' list1′, ' ab0′);
$redis->rpush (' list1′, ' ab1′); $redis->rpush (' list2′, ' ab2′);
$redis->rpush (' list2′, ' ab3′); $redis->rpoplpush (' list1′, ' list2′);//Results List1 =>array (' ab0′ '), List2 =>array (' ab1′, ' ab2′, ' ab3′ ') $redis->
Rpoplpush (' list2′, ' list2′);//apply to the same queue, move the last element to the head list2 =>array (' ab3′, ' ab1′, ' ab2′ ')//linsert insert elements before or after the specified element in the middle of the queue $redis->linsert (' list2′, ' before ', ' ab1′, ' 123′);   The expression is inserted before the element ' ab1′ ' 123′ $redis->linsert (' list2′, ' after ', ' ab1′, ' 456′); Indicates that after the element ' ab1′ insert ' 456′//blpop/brpop block and wait for a queue to be empty, pop out the leftmost or leftmost element (this feature is very useful outside of PHP)//brpoplpush is also blocking and waiting for operations, The result is the same as Rpoplpush $redis->blpop (' list3′,10);
If List3 is empty, it waits until the first element is ejected, after 10 seconds Timeout/** Set table operation * *//sadd add element, return True, repeat return false $redis->sadd (' set1′, ' ab ');
$redis->sadd (' set1′, ' CD ');

$redis->sadd (' set1′, ' ef '); Srem removes the specified element $redis->srem (' set1′, ' CD ');

Remove the ' CD ' element//spop eject the first element $redis->spop (' set1′);
Smove moves the specified element of the current set table to another set table $redis->sadd (' set2′, ' 123′); $redis->smove (' set1′, ' set2′, ' ab ');/move ' ab ' to ' set2′ in ' set1′, return TRUE or False//scard returns the number of elements in the current set table $redis->scard ( ' set2′ ');/2//sismember Determine whether the element belongs to the current table $redis->sismember (' set2′, ' 123′); True or False//smembers returns all elements of the current table $redis->smembers (' set2′);

Array (' 123′, ' ab ');
Sinter/sunion/sdiff returns the intersection/set/complement of elements in two tables $redis->sadd (' set1′, ' ab '); $redis->sinter (' set2′, ' set1′);
Returns array (' AB ')//sinterstore/sunionstore/sdiffstore two table intersection/set/complement element copy to third table $redis->set (' foo ', 0); $redis->sinterstore (' foo ', ' set1′ '); This is equivalent to copy ' set1′ ' content to ' foo ' and convert ' foo ' to set table $redis->sinterstore (' foo ', Array (' set1′, ' set2′));

Copy the same elements in ' set1′ ' and ' set2′ ' into the ' Foo ' table, overwriting the original contents of ' Foo '//srandmember returning a random element in the table $redis->srandmember (' set1′ ');
/** ordered Set Table operation * *//sadd add element and set ordinal number, return True, repeat return false $redis->zadd (' zset1′,1, ' ab ');
$redis->zadd (' zset1′,2, ' CD ');

$redis->zadd (' zset1′,3, ' ef '); Zincrby the increment or decrease of the index value of the specified element, changing the order of elements $redis->zincrby (' zset1′,10, ' ab ');/return one//zrem remove the specified element $redis->zrem (' zset1′, ' EF '); True or False//zrange the elements of the specified interval in the table by position order $redis->zrange (' zset1′,0,1); Returns elements between positions 0 and 1 (two) $redis->zrange (' zset1′,0,-1);Returns the element (equivalent to all elements) between position 0 and the penultimate element//zrevrange ibid, returns the elements of the specified interval in the table, inverted in order $redis->zrevrange (' zset1′,0,-1);
Element order and Zrange reverse//zrangebyscore/zrevrangebyscore returns the elements of the specified index interval in the table in order/descending $redis->zadd (' zset1′,3, ' ef ');
$redis->zadd (' zset1′,5, ' gh '); $redis->zrangebyscore (' zset1′,2,9); Returns the element array between the index value 2-9 (' ef ', ' gh ')//parametric form $redis->zrangebyscore (' zset1′,2,9, ' withscores '); Returns the element between the index value 2-9 and contains the index value array (' EF ', 3), array (' GH ', 5)) $redis->zrangebyscore (' Zset1′,2,9,array ') (' Withscores ' =>true, ' Limit ' =>array (1, 2)); Returns the element between the index value 2-9, the ' Withscores ' =>true representing the index value; ' Limit ' =>array (1, 2), which indicates a maximum return of 2, with the result array (' EF ', 3), array (' GH ', 5)//zunionstore/zinterstore the collection of multiple tables/ The intersection is deposited into another table $redis->zunionstore (' Zset3′,array (' zset1′, ' zset2′, ' zset0′ '); The ' zset1′ ', ' zset2′ ', ' zset0′ ' and ' set ' are deposited in ' zset3′//other parameters $redis->zunionstore (' Zset3′,array, ' zset1′ '), Array (' Weights ' => Array (5,0));//weights parameters represent weights in which elements representing a set of values greater than 5 are ranked before, and greater than 0 in the rear $redis->zunionstore (' Zset3′,array ′, ' zset2′ ', Array (' aggregate ' => ')Max ');//' Aggregate ' => ' max ' or ' min ' indicates that the same element is a large value or a small value//zcount the number of elements in an index interval $redis->zcount (' zset1′,3,5);//2 $redis->zcount (' zset1′, ' (3′,5)); ' (3′ indicates that the index value is between 3-5 but does not contain 3, and can also use ' (5′ for the upper limit of 5 without 5//zcard statistic elements $redis->zcard (' zset1′ ');//4//zscore Query element index $redis- >zscore (' zset1′, ' ef ');//3//zremrangebyscore Deletes an element of an index interval $redis->zremrangebyscore (' zset1′,0,2); Deletes the element between 0-2 (' AB ', ' CD '), returns the number of deleted elements 2//zrank/zrevrank the table order/descending position of the returned element (not the index) $redis->zrank (' zset1′, ' ef ');/return 0, Because it is the first element; Zrevrank returns 1 (the last)//zremrangebyrank the element that deletes the specified position interval in the table $redis->zremrangebyrank (' zset1′,0,10); Deletes the element with a location of 0-10, returns the number of deleted elements 2/** hash table operation///hset/hget access hash table data $redis->hset (' hash1′, ' key1′, ' v1′);
The elements of the key as ' key1′value ' v1′ are deposited into the HASH1 table $redis->hset (' hash1′, ' key2′, ' v2′);  $redis->hget (' hash1′, ' key1′); Takes out the value of key ' key1′ in the table ' hash1′, returns ' V1′//hexists returns whether the specified key in the hash table exists $redis->hexists (' hash1′, ' key1′); True or False//hdel deletes the element of the specified key in the hash table $redis->hdel (' hash1′, ' key2′); True or False//hlenReturns the number of hash table elements $redis->hlen (' hash1′); 1//hsetnx adds an element, but cannot repeat $redis->hsetnx (' hash1′, ' key1′, ' v2′); False $redis->hsetnx (' hash1′, ' key2′, ' v2′);
True//hmset/hmget access multiple elements to the hash table $redis->hmset (' Hash1′,array (' key3′=> ' v3′, ' key4′=> ' v4′)); $redis->hmget (' Hash1′,array (' key3′, ' key4′); Returns the corresponding value array (' v3′, ' v4′)//hincrby to the specified key $redis->hincrby (' hash1′, ' key5′,3); Return 3 $redis->hincrby (' hash1′, ' key5′,10); Returns the//hkeys returns all key $redis->hkeys (' hash1′) in the hash table; Returns Array (' key1′, ' key2′, ' key3′, ' key4′, ' key5′ ')//hvals returns all value $redis->hvals (' hash1′) in the hash table; Returns the array (' v1′, ' v2′, ' v3′, ' v4′,13)//hgetall returns the entire hash table element $redis->hgetall (' hash1′); Return Array (' key1′=> ' v1′, ' key2′=> ' v2′, ' key3′=> ' v3′, ' key4′=> ' v4′, ' key5′=>13 ')/** sort Operations///sort sort $
Redis->rpush (' tab ', 3);
$redis->rpush (' tab ', 2);
$redis->rpush (' tab ', 17);  $redis->sort (' tab '); Returns array (2,3,17)//usage parameters, which can be combined using array (' sort ' => ' desc ', ' limit ' => array (1, 2)) $redis->sort (' tab', array (' sort ' => ' desc '));  Descending order, returning array (17,3,2) $redis->sort (' tab ', Array (' Limit ' => array (1, 2)); Returns 1 of the elements in the order position 2 (where 2 is the number, not the position), returning array (3,17) $redis->sort (' tab ', Array (' Limit ' => array (' alpha ' => true)) ; Sort by first character returns array (17,2,3), because the first character of 17 is ' 1′ so row first is placed $redis->sort (' tab ', Array (' Limit ' => array (' Store ' => ' ordered ') )); Represents a permanent sort that returns the number of elements $redis->sort (' tab ', Array (' Limit ' => array (' Get ' => ' pre_* ')); The wildcard ' * ' filter element is used to return only elements that start with ' pre_ '/** redis admin Operations///select Specify the database to be manipulated $redis->select (' mydb ');

Specified as MyDB,//FLUSHDB is created to empty the current library $redis->flushdb ();
Move moves when the elements of the library to other libraries $redis->set (' foo ', ' Bar '); $redis->move (' foo ', ' mydb2′ ');

If ' mydb2′ inventory in//info display service when state information $redis->info (); Slaveof configuration from the server $redis->slaveof (' 127.0.0.1′,80); The server configuring 127.0.0.1 port 80 is $redis->slaveof () from the server;
Purge server data from server//sync to disk $redis->save ();
Asynchronously save server data to disk $redis->bgsave ();
//??
$redis->bgrewriteaof ();

Returns the last time the disk was updated $redis->lastsave (); Set/get multiple Key-value
$mkv = Array (' usr:0001′=> ', ' usr:0002′=> ' Second user ', ' usr:0003′=> ' third user '); $redis->mset ($mkv); Stores the value $retval for multiple keys = $redis->mget (Array_keys ($mkv));

Gets the value Print_r ($retval) corresponding to multiple keys; Bulk Operation $replies = $redis->pipeline (function ($pipe) {$pipe->ping (); $pipe->flushdb (); $pipe->incrby (' Counter ', 10);
Incremental Operation $pipe->incrby (' counter ', 30);
$pipe->exists (' counter ');
$pipe->get (' counter ');
$pipe->mget (' does_not_exist ', ' counter ');
});

Print_r ($replies); CAS, transactional operation function Zpop ($client, $zsetKey) {$element = null; $options = Array (' CAs ' => true,//Initialize W        ITH support for CAS operations ' watch ' => $zsetKey,//Key This needs to is watched to detect changes ' retry ' => 3,
Number of retries on aborted transactions, after//which the client bails out with a exception.

); $txReply = $client->multiexec ($options, function ($TX) use ($zsetKey, & $element) {@list ($element) = $tx->zraNge ($zsetKey, 0, 0);     if (Isset ($element)) {$tx->multi ();
With CAS, MULTI *must* is explicitly invoked.
$tx->zrem ($zsetKey, $element);
}
});
return $element;
$zpopped = Zpop ($redis, ' zset '); echo isset ($zpopped)?

"Zpoped $zpopped": "Nothing to zpop!", "\ n";

Prefix the access key, such as: ' NRK: ' $redis->getprofile ()->setpreprocessor (New Keyprefixpreprocessor (' NRK: '); Some methods of distributed storage $multiple _servers = Array (' Host ' => ' 127.0.0.1′, ' Port ' => 6379, ' database ' => 15, ' Alias ' => ',), Array (' Host ' => ' 127.0.0.1′, ' Port ' => 6380, ' database ' =>, ' Alias ' =& Gt

' Second ',),);

Use Predis\distribution\idistributionstrategy;

Class Naivedistributionstrategy implements Idistributionstrategy {private $_nodes, $_nodescount;

Public Function __constructor () {$this->_nodes = array (); $this->_nodescount = 0;}

Public function Add ($node, $weight = null) {$this->_nodes[] = $node; $this->_nodescount++;} Public function Remove ($node) {$this->_nodes = Array_filter ($this->_nodes, function ($n) use ($node) {return $n!== $node;}); $thi
S->_nodescount = count ($this->_nodes); The Public function get ($key) {$count = $this->_nodescount; if ($count = = 0) {throw new RuntimeException (' No connecti
ONS ');
return $this->_nodes[$count > 1 abs (CRC32 ($key)% $count): 0];

Public Function GenerateKey ($value) {return CRC32 ($value);}}

Configure the key distribution policy $options = Array (' key_distribution ' => new Naivedistributionstrategy ());

$redis = new Predis\client ($multiple _servers, $options);

for ($i = 0; $i set ("Key: $i", Str_pad ($i, 4, ' 0′, 0)); $redis->get ("Key: $i");
$server 1 = $redis->getclientfor (' a ')->info ();

$server 2 = $redis->getclientfor (' second ')->info (); printf (' Server '%s ' has%d keys while server '%s ' has%d keys.\n ', ' ' a ', $server 1[' db15 '] [' Keys '], ' second ', $server 2[' DB15 ' [' Keys ']




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.