Getting Started with Redis

Source: Internet
Author: User
Tags set set redis cluster install redis

Brief introduction

Remote Dictionary Server (Redis)
Redis is an open source high-performance key-value pair database. It adapts to the storage requirements of different scenarios by providing multiple key-value data types, and uses many high-level interfaces to make them capable of different roles such as caching, queue systems, and so on.

It is similar to memcached, but the data can be persisted and the supported data types are rich.

As of June 27, 2015, the latest stable version released was 3.0.2.
The largest upgrade of the 3.0 version is the Redis cluster, a distributed Redis example with automatic data fragmentation and high fault tolerance, as well as increased speed in the case of high loads.

Install, configure the installation

Download path: http://redis.io/download

安装命令$ wget http://download.redis.io/releases/redis-3.0.2.tar.gz$ tar xzf redis-3.0.2.tar.gz$ cd redis-3.0.2$ make启动$ src/redis-server客户端$ src/redis-cliredis> set foo barOKredis> get foo"bar"
Configuration

REDIS configuration sample file under%redis_home% redis.conf
Contains many default configurations
Use configuration to do this: $ redis-server/etc/redis/6379.conf

Daemonize If you need to run in the background, change the entry to Yespidfile to configure multiple PID addresses, by default in/var/run/redis.pidbind bound IP, set only to accept requests from that IP port listening ports, The default is 6379timeout to set the time-out for client connections, in seconds loglevel divided into 4 levels, debug, verbose, notice, warninglogfile configuration log file address databases set the number of databases, The database used by default is0save set the frequency of Redis for database mirroring and how often snapshots are saved.    The first parameter represents how long, and the second represents how many times the write operation takes. Snapshots are automatically saved when a certain number of writes are performed within a certain amount of time. You can set multiple conditions. Rdbcompression When a mirrored backup is made, whether to compress the file name of the dbfilename image backup file dir database mirror backup files placement path slaveof set the database as a slave database for the other database Masterauth Password Authentication required for primary database connection Requirepass set the password to use when logging on maxclients limit the number of simultaneous clients maxmemory set the maximum memory that Redis can use appendonly turn on Append only mode Appendfsync sets the frequency of appendonly.aof file synchronization vm-enabled whether virtual memory is supported vm-swap- file set the swap file path for virtual memory Vm-max- Memory set maximum physical memory size used by Redis vm-page-size set the page size of virtual memory vm-pages set the total page number of the interchange file Vm-max-threads set Vmio number of simultaneous threads Glueoutputbuf store small output cache together hash-max-zipmap-entries set hash critical value activerehashing re- hash             

For details, please refer to: http://t.cn/8kr3HUw

Data structures and their usage scenarios

1 string Character type
2 Hash Hash type
3 List Type
4 Set Set type
5 sorted set ordered set

string literal type

The string type is the most basic data type of redis and is the basis for other 4 data types.

command description example
SET key Valu E Assignment set foo 5 ==> OK
GET key take value GET foo ==& Gt "5"
INCR key increment. The key does not exist when you create and assign 0, otherwise +1 INCR foo ==> 6
DECR Key Decrement decr foo ==> 5
incrby key num is the same as INCR, but can specify an increased value incrby foo 5 ==>
APPEND key value Append, return string length after append APPEND foo ==> 4
STRLEN key length STRLEN foo ==> 4
MSET key value[key value ...] set multiple key values at the same time mset key1 1 key2 2 ==> OK
MGET key[key ...] get multiple key values at the same time mget key1 key2 ==> "1" "2"

The string is introduced here, and there are other commands to see the official documents yourself??????

Hash hash type

A hash type is a key-value data structure whose value can only be a string, that is, the hash data type does not support nesting of other data types.

Command Description Example
Hset key field value Set or modify field values Hset User name Frek ==> 1
Hget key Field Get field values Hget User name ==> "Frek"
Hmset key field value[field value:] Set multiple fields at the same time Hmset User name Frek age ==> OK
Hmget key field[field:] Get multiple field values at the same time Hmget User name Age ==> "Frek" "18"
Hgetall Key Get all fields and values in a key Hgetall user ==> "name" "Frek" "Age" "18"
Hexists key Field Determines whether the field exists, returns 1, otherwise returns 0 (returns 0 if the key does not exist) Hexists User Email ==> 0
Hsetnx key field value Assign a value when the field does not exist HSETNX user name Sam ==> 0; HSETNX user Email [email protected] ==> 1
Hincrby key field Increment Refer to the Incrby command Hincrby User Age 1 ==> 19
Hkeys Key Get all field names in a key Hkeys user ==> "name" "Age" "Email"
Hvals Key Get all the field values Hvals user ==> "Frek" "[Email protected]"
Hlen Key Get the number of fields Hlen User ==> 3
Hdel key field[field:] Delete one or more fields, returning the number of deleted fields Hdel User Email Age ==> 2
List type

List types can store an ordered list of strings

Command Description Example
Lpush key value[Value:] Adds an element to the left of the list, returning the length of the list after adding the element Lpush users Fred Sam Alice ==> 3
Rpush key value[Value:] Add an element to the right of the list Rpush users Carl Lisa Nicesu ==> 6
Lpop Key Removes an element from the left side of the list and returns the element value Lpop users ==> "Fred"
Rpop Key Removes an element from the right side of the list and returns the element value Rpop users ==> "Nicesu"
Llen Key Returns the number of list elements and returns 0 if the key does not exist Llen users ==> 1
Lrange Key Start stop Get list fragments, start and stop support negative numbers,-1 indicates the first of the right number Lrange users 0-1 ==> "Sam" "Alice" "Carl" "Lisa"
Lrem Key Count value Removes the specified value from the list, returning the number of deleted elements Lrem users 2 Sam ==> 1
LINDEX Key Index Gets the value of the specified index element Lindex users 0 ==> "Carl"
LSET Key index value Sets the element value for the specified index LSet users 0 Allen ==> OK
LTRIM Key Start end Keep only the list of specified fragments, delete other elements LTrim users 0 1 ==> OK
Linsert Key Before/after Pivot value Inserts an element into the list, returning the inserted list length Linsert users after Carl Adam ==> 3
Rpoplpush Source Destination Moves an element from one list to another, executes a rpop on the source, executes a lpush on the destination, returns the element value that was moved Rpoplpush users usernames ==> "Adam"
Collection type

Each element in the collection is different and has no order

Command Description Example
Sadd key member[member ...] Add one or more elements Sadd tags one three ==> 3
Srem key member[member ...] To remove one or more elements Srem Tags ==> 1
Smembers Key Gets all the elements in the collection Smembers tags ==> "three" "One"
Sismember Key Member Determines whether an element exists in the collection Sismember tags one ==> 1
SCard Key Gets the number of elements of the collection SCard Tags ==> 2
Srandmember key[Count] Returns 1 or count of random elements Srandmember tags ==> "one"
Sdiff key[key..] Set difference operation
SINTER key[key..] Set intersection operation
Sunion key[key..] Set and set operations
Ordered collection types

An ordered collection type that is based on a collection type has a fraction associated with each element, which allows us to work with fractional operations in addition to the operation of the collection type.

Command Description Example
Zadd Key score member[score member ...] Add an element with a fraction, and if it already exists, replace the fraction Zadd scoreboard Fred, Parker, Tony Nicesu ==> 4
Zscore Key Member Get element Score Zscore Scoreboard Nicesu ==> "59"
Zrange key start end[withscores] Gets the element ranked in a range, returning an element sorted in ascending order of score Zrange scoreboard 0-1 ==> "Nicesu" "Fred" "Tony" "Parker"
Zrevrange key start end[withscores] Consistent with Zrange, returns the element descending by score Zrevrange Scoreboard 0-1 withscores ==> "Parker" "" "" "" Tony "" "" "Fred" "" "" Nicesu "" 59 "
Zrangebyscore key min max[withscores][limit offset Count] Gets the element within the specified fractional range Zrangebyscore Scoreboard ==> "Fred" "Tony" "Parker"
Zrevrangebyscore key Max min[withscores][limit offset Count] Gets the elements within the specified fractional range, sorted in descending order Zrevrangebyscore Scoreboard ==> "Parker" "Tony" "Fred"
Zincreby Key Increment member Increase the score of an element Zincrby Scoreboard 1 Nicesu ==> 60
Zcard Key Gets the number of elements in the collection Zcard Scoreboard ==> 4
Zcount KEY min Max Gets the number of elements in the specified fraction range Zcount Scoreboard ==> 1
Zrem key member[member ...] Delete one or more elements Zrem Scoreboard Nicesu ==> 1
Zrank Key Member Get fractions from small to large sort of position Zrank Scoreboard Parker ==> 2
Zrevrank Key Member Ditto Zrevrank Scoreboard Parker ==> 0
Zremrangebyrank Key Start stop Delete Elements by rank range
Zremrangebyscore Key min Max Delete Elements by fractional range
Redis and node. JS Installation:

npm install redis
You can also install Redis libraries written in C
npm install hiredis redis
If Hiredis,node_redis is installed, the library provided by the Hiredis is called by default

Example:
    var Redis =Require"Redis"),Redis.createclient (port, host, option) client = Redis.createclient (6379,' 127.0.0.1 ', {auth_pass:' Password '});If you need to switch the database, do the followingClient.select (3, function () {/* ... */}); Client.on ("Error",function(ERR) {Console.log ("Error" + Err);}); Client.set ("String Key","String Val", Redis.print); Client.hset ( "hash key",  "Hashtest 1",  "some value" ", Redis. print); Client.hset ([ "hash key",  "Hashtest 2",  "some other value"], Redis. print); Client.hkeys ( "hash key",  function  (err, replies) {Console.log (replies.length +  "replies: "); Replies. foreach (function  (reply, i) {Console.log ( ":" + Reply);}); Client.quit (); }); 

Like Mset can be multi-parameter commands, parameters can be used in the way of arrays:
client.mset(key1, val1, ... keyn, valn, [callback]);
Equivalent to
client.mset([key1, val1, ... keyn, valn], [callback]);

Hmset can accept multiple parameters and objects
client.hmset(hashkey, key1, val1, ... keyn, valn, [callback])
Equivalent to
client.hmset(hashkey, obj, [callback])



Wen/elson (author of Jane's book)
Original link: HTTP://WWW.JIANSHU.COM/P/BD3550784BCE
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Getting Started with Redis

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.