Application of Redis in ASP.

Source: Internet
Author: User
Tags install redis redis server

1.redis Introduction

As a supplement to relational database, NoSQL database has been widely used in internet companies. Redis is one of the representatives, Redis is a (key,value) memory-based database, and supports a variety of data structures, such as list,hashset,string, and can support the persistent storage of data, Redis How to do memory data to disk synchronization will be explained in separate chapters. Since Redis is a memory-based database, it will be applied to applications where performance requirements are high, such as data caching, which can reduce the stress of database access. At the same time Redis can be applied in the statistical analysis of the Web application, statistical analysis of the Web application, generally read from the database and related calculations of large amounts of data, so data preprocessing can be pre-calculated data, and (Key,value) in the form of a redis, This can greatly improve the query performance.

2.redis is used under Windows.

Redis is widely used under Linux. The official website is: Http://redis.io/,window under the Redis official does not provide support, but can download the WINDOWS64 version of Redis in Http://redis.io/download, is by Microsoft Open Tech Group development and maintenance, open source code to post on GitHub: Https://github.com/MSOpenTech/redis. In addition, an. exe executable file is provided that supports 32bit and 64bit:https://github.com/rgl/redis/downloads.

After you download the Redis.exe file, after you install Redis, it appears in the corresponding Redis root directory: Redis-cli.exe,redis-server.exe,redis-service.exe, corresponding to the Redis client, respectively. Service-side and Redis service launcher. After opening separate Redis-server.exe and Redis-cli.exe, enter the command on the REDIS-CLI command line to send read and write commands to the Redis server, and you can see that the client connection is displayed on the Redis-server command line. As shown in the following:

  

Figure 1.redis-server Run diagram

Figure 2.redis-cli Run diagram

Next we read and write the Redis server database through a simple C # console program.

3.c# Connect to the Redis server database.

At present, the most common Redis client C # class libraries are: Stackexchange.redis and Servicestack.redis, The main use of this article is that Stackexchange.redis,stackexchange is a high-performance client class library that provides both synchronous and asynchronous operations. After installing Stackexchange through NuGet, you can connect to Redis server through it.

A Connectionmultiplexer class is provided in Stackexchange that masks the details of the underlying multi-Redis server connection, which is designed to be shared and reused by multiple callers of the client. Therefore, you do not have to create a new Connectionmultiplexer object each time you operate on a redis operation. At the same time, the object's operations are designed to be thread-safe. In order to establish a connection to Redis server, we can use the following methods:

Connectionmultiplexer con = connectionmultiplexer.connect ("localhost:6379"), Redis Server default port is 6379.

To reuse the Connectionmultiplexer object, we can use the object by defining a static property and returning an instance of Connectionmultiplexer. Next we'll write a simple singleton pattern to get the Connectionmultiplexer object. The code is as follows:

       Public class redisconnection    {        privatestaticreadonlynew lazy<connectionmultiplexer> (() = > Connectionmultiplexer.connect ("localhost:6379"));          Public Static Get return _connection. Value; } }    }

A Connectionmultiplexer instance is created by a fall-load, and the initialization of the instance is thread-safe.

Next we test the read and write operations on the Redis server by defining a simple client.

 classProgram {Static voidMain (string[] args) {Connectionmultiplexer con=redisconnection.connection; Idatabase DB=con. Getdatabase ();//The default is to connect to database 0 db. Stringset ("name","Tom"); stringValue = db. Stringget ("name"); Console.WriteLine ("Name:"+value); }    }

The execution result of the program is: Name:tom.

Next we write a simple object to store in Redis.

First we define a student class:

     Public classStudent { Public intId {Get;Set; }  Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public stringSchool {Get;Set; } }

Since Redis needs to serialize the object first before it is stored, it needs to be deserialized when the object is read, and then we will define two idatabase extension methods.

  Public Static classredisextension { Public StaticTResult get<tresult> ( ThisIdatabase Cache,stringkey) {            returnDeserialize<tresult>(Cache.        Stringget (key)); }         Public Static voidSet<tin> ( ThisIdatabase Cache,stringkey, TIn value) {Cache.        Stringset (Key, Serialize (value)); }        Static byte[] Serialize (Objecto) {if(O = =NULL)                return NULL; BinaryFormatter BinaryFormatter=NewBinaryFormatter (); using(MemoryStream mstream =NewMemoryStream ())                {binaryformatter.serialize (mstream,o); byte[] Objectdataasstream =Mstream.toarray (); returnObjectdataasstream; }        }        StaticTResult deserialize<tresult> (byte[] stream) {            if(Stream = =NULL)                return default(TResult); BinaryFormatter Formatter=NewBinaryFormatter (); using(MemoryStream Memstream =NewMemoryStream (Stream)) {TResult result=(TResult) formatter.                Deserialize (Memstream); returnresult; }        }            }

Next we define a client to test the use of the Redis object's read and write:

 classProgram {Static voidMain (string[] args) {Connectionmultiplexer con=redisconnection.connection; Idatabase DB=con.            Getdatabase (); Student St=NewStudent {age = A, Name ="Tom", School ="mit" }; Db. Set ("Student", ST); Console.WriteLine ("Name:"+ St. Name +"Age :"+St.        Age); }    }

After running the program, the program throws an exception, prompting student not to indicate Serializable, adding the [Serializable] property on the student class, after running the program, the result output: Name:tom age:12.

Next we are going to write a simple Web API example to demonstrate the use of Redis as a cache in the Web API, basically the same as using Redis in C # console, except for some extra processing on object return.

After creating a new Web API project in VS, we simply build a studentcontroller.

The invocation of the class method used in this example is the same as in the previous example. And for the sake of convenience, I wrote all the operations in the controller.

namespace mvcapplication3.controllers{public    class Studentcontroller:apicontroller    {public        Student Get (int id)        {            string cacheKey = "Getstudent:" + ID;                       Connectionmultiplexer con = redisconnection.connection;            Idatabase db = con. Getdatabase (1);            Student stobj = db. Get<student> (CacheKey);            if (stobj! = null)            {                return stobj;            }            Student st = new Student {Id = 1, age = n, Name = "Tom", School = "USTC"};            Db. Set (cachekey,st);            Return St;}}    }

We use Fiddler to see the results of the objects returned by the server side. Enter: HTTP://LOCALHOST:8536/API/STUDENT/1 in the URL box to view the results of JSON data returned by the server side:

We can see the information of the returned field, which is not what we expected, because we are using the automatic set Get property when we define the Sudent class, and when the C # compiler compiles the IL code, it generates information about the fields of the corresponding property, and the generated field names are the corresponding information. By default, the Web API serializes object fields and automatic attributes before the object is returned, and when we represent the [Serializable] property for a class, only the field information is serialized, and in order to serialize the corresponding property, we need to define the following class of student:

[Serializable] [DataContract] Public classStudent {[DataMember] Public intId {Get;Set; } [DataMember] Public stringName {Get;Set; } [DataMember] Public intAge {Get;Set; } [DataMember] Public stringSchool {Get;Set; } }

At this point, we are running the application, enter URL:HTTP://LOCALHOST:8536/API/STUDENT/1, and return the JSON data as follows:

Get the results we need, of course, in the Web API we can also do this in the following way. The default JSON serializer ignores the [Serializable] property:

Make the following settings in the Global.aspx App_start method:

var serializersettings =   GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; var contractresolver =  true;

At this point, the simple use of Redis in C # is introduced here!

Application of Redis in ASP.

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.