Basic supplements------Redis Detailed

Source: Internet
Author: User
Tags delete key redis server

Basic supplements

Basic supplements------Redis Detailed

Basic supplements------Reflection

Basic supplements------commissioned detailed

Basic supplements------Interface Detailed

Basic supplements------Generic explanation

Objective

This article differs from the previous base supplements, which was previously introduced in C # Fundamentals, and today is about Redis. Because one of the projects is in use, I think that most of the projects now use NoSQL, caching, and today we're going to introduce Redis. Say less nonsense and start with the subject.

What is 1.redis?

Redis is fully open source free, adheres to the BSD protocol and is a high-performance Key-value database .

The right Redis is a database of key-value pairs that not only support simple key-value-type data, but also provide storage for data structures such as List,set,zset,hash. "I'm used to saving simple Key-value (value is written for objects that require data structures)".

2.redis Usage Scenarios

1. Take the latest N data operation

2. Leaderboard application, top N operation

3. Applications that need to set the expiration time accurately

4. Counter Application

Since the incr and other directives themselves have the characteristics of atomic operations, we can fully utilize Redis's incr, Incrby, DECR, Decrby and other instructions to achieve the atomic count effect, if, in a certain scenario there are 3
The client reads the value of the mynum at the same time (a value of 2) and then adds 1 to it at the same time, then the value of the last Mynum must be 5. Many websites use this feature of Redis to achieve statistical counting requirements on the business.

5.Uniq operation to get all data rows for a certain period of time

6. Real-time system, anti-spam system

7.pub/sub Building a real-time messaging system

8. Build a queue system

  9. Caching

Most are used for caching. His operation is 10 times times more than MySQL's reading. The set operation is 110,000 times per second, and the get operation is 81,000 times per second.

3.REDIS Data Structure

It's already been said. Redis is an advanced Key:value storage system in which value supports five types of data:

1. String (strings)
2. String list (lists)
3. String collection (sets)
4. Ordered string collection (sorted sets)
5. Hash (hashes)

3.1.key

1.key not too long, try not to exceed 1024 bytes, which not only consumes memory, but also reduces the efficiency of the search;
2.key also not too short, too short, the readability of key will be reduced;
3. In a project, key is best used in a unified naming scheme, such as Power_loginname

3.2. String (Strings)

The strings type is a very basic data type and is a necessary data type for any storage system.

The operation is as follows:

Set ' Kmonkeywyl ' Get Myredis

Note: When encountering a non-string type such as Int,redis, it is converted to string by default.

3.3. String list (lists)

The lists in Redis is not an array, but a list of the underlying implementations. So the insertion of data is fast, but the positioning performance operation is poor.

Common operations of lists include Lpush, Rpush, Lpush,lrange, etc.

The operation is as follows:

//Create a new list called MyList, and insert the element "1" in the head of the listLpush MyList"1"//Insert Element "2" to the right of MyListRpush MyList"2"//Insert Element "0" to the left of MyListLpush MyList"0"//list elements from number 0 to number 1 in the MyListLrange MyList0 1//List MyList from number 0 to the first element in the countdownLrange MyList0-1 

Note: The above application scenario 1,2,8 all use lists will be very convenient, specific application scenarios (Message Queuing, paging, blog comments)

3.3. String collection (sets)

Collection for us should not be unfamiliar, is our first high school of the collection, for the collection there are several concepts do not know you are familiar with it? Take the intersection, take the set, take the difference, not familiar with yourself to go.

The operation is as follows:

//Add the new element "Wyl" to the collection MySetSadd MySet"Wyl"(integer)1Sadd MySet"Kmonkey"(integer)1//list all elements in the collection MySetsmembers MySet1)"Wyl"2)"Kmonkey"//determines whether element 1 is in the collection MySet, and returns 1 that indicates the existenceSismember MySet"Wyl"(integer)1//determines whether the element is in the collection MySet and returns 0 to indicate that it does not existSismember MySet"wangyanling"(integer)0//Create a new collection YoursetSadd Yourset"1"(integer)1Sadd Yourset"2"(integer)1smembers Yourset1)"1"2)"2"//set of two setssunion MySet Yourset1)"1"2)"Wyl"3)"2"4)"Kmonkey"
3.4. Ordered string collection (sorted sets)

The only difference between the top and the other without a set is that each element in order has an ordinal score, which is primarily easy to sort

The operation is as follows:

Zadd Myzset1baidu.com (integer)1//Add an element 360.com to Myzset and give it a sequence number of 3Zadd Myzset3  the. com (integer)1//add an element to the Myzset google.com, giving it a sequence number of 2Zadd Myzset2google.com (integer)1//list all the elements of Myzset, and list their serial numbers, you can see that myzset is already orderly. Zrange Myzset0-1With scores1)"baidu.com"2)"1"3)"google.com"4)"2"5)"360.com"6)"3"//list only elements of MyzsetZrange Myzset0-11)"baidu.com"2)"google.com"3)"360.com"
3.5. Hash (hashes)

This is similar to the structure database. I don't like using hashes in Redis.

Operation is as follows

//establish a hash and assign a valueHmset User:001Username Wylpassword111Age theOK//List the contents of a hash127.0.0.1:6379> Hgetall User:0011)"username"2)"Wyl"3)"Password"4)"111"5)" Age"6)" the"//change one of the values in the hashHset User:001Password12345(integer)0//List The contents of the hash again127.0.0.1:6379> Hgetall User:0011)"username"2)"Wyl"3)"Password"4)"12345"5)" Age"6)" the"
4.redis Common directives

4.1. Key-Value related commands

Keys * Take out all current key

exists key to see if key exists

Del key Delete key

Expire key Setting key expires

TTL key gets the effective duration of key

Select 0 Choose to 0 database redis default database is 0~15 altogether 16 databases

Move Key1 The key in the current database to a different database

Persist key to remove key expiration time

Random key randomly returns a key inside the database

Rename Key2 key3 rename Key2 to Key3

Type Key2 returns the data type of key

4.2. Server-related commands

Ping pong Returns whether the response was successfully connected

Echo Prints some content on the command line

Select 0~15 Number of databases

Quit/exit exiting the Client

Dbsize returns the number of all keys in the current database

Info returns information about Redis

Config get dir/* real-time upload of received requests

FLUSHDB Delete all keys in the currently selected database

Flushall Delete a database from all databases

4.3. Operation of String type

Set key value exists on modify, does not exist to create

Get key value

Mset key1 value1 Key2 value2 set multiple values at once

Mget key1 Key2: Get multiple values at once

Simple on these people can go further online search, because too much I wrote in this section.

5.c# instances

(1) The first is the Redis connection service base class.

  Public Abstract classBaseredis {Privateiredisclient _client; Private string_configuration_string;  PublicBaseredis () {} PublicBaseredis (stringconfiguration_string) {             This. _configuration_string =configuration_string; }         Public voidSet_configuration_string (stringconfiguration_string) {             This. _configuration_string =configuration_string; }         Publiciredisclient RS {Get            {                if(string. Isnullorwhitespace ( This. _configuration_string)) {                    return NULL; }                if( This. _client = =NULL)                {                     This. _client =NewRedisclient ( This. _configuration_string); }                return  This. _client; }        }    }
View Code

(2) configuration file

Where the path can be directly written to the server IP address. I write him as a string, is for the development of the environment and it is not the environment to modify the program, directly do IP mapping on the line.

(3) Connect to Redis server

 Public class Dbperfmon:redishelper    {        public  Dbperfmon ()            base()        {            string Myredis = configurationmanager.appsettings["redis_server_url_perfmon"]. ToString ();            Set_configuration_string (Myredis);        }

(4) Simple operation

  Lock(sessionlocker) {if(string. IsNullOrEmpty (Synkey) | | user = =NULL)                    return string.                Empty; Sessionobject So=NULL; using(RS) {//Get Redis valueso = Rs. Get<sessionobject>(Synkey); if(So! =NULL) {so.                        Resetlasttime (); if(!So . Iseffective ()) {so. Signtype=Signtype; So. User=user; }                    }                    Else{ So=Newsessionobject (user, Signtype, synkey); }} DateTime DT= DateTime.Now.AddMinutes ( -);//Add RedisRs. Set<sessionobject>(Synkey, so);//Set Effective DurationRs.                Expireentryat (synkey, DT); returnSo .            Id; }

Basic supplements------Redis Detailed

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.