1. Install the NuGet package required by the. NET Operations Redis:
here recommended for: Stackexchange.redis, enter command install-package in Package Manager console Stackexchange.redis
2. Write the implementation code under action:
Public classHomecontroller:controller {Private ReadOnly Static stringKeyperfix ="Test_clicktotal_"; //Get:home Public AsyncTask<actionresult> Index (intId=0) { using(Connectionmultiplexer Redis = Connectionmultiplexer.connect ("localhost:6379") ) {Idatabase db= Redis. Getdatabase (4);//The redis default has 15 databases, and the parameters in Getdatabase () represent the data being stored in that data awaitDb. Stringincrementasync (Keyperfix+id,1);//high efficiency by using Stringincrementasync for counting stringTotal =awaitDb. Stringgetasync (Keyperfix + Id);//added after reading outClicktotalmodel Totalmodel =NewClicktotalmodel {total=Convert.ToInt32 (total)}; returnView (Totalmodel); } } }
3. Debug results:
Each time the refresh enters the interface, the number of clicks is incremented once.
4. Of course there is a problem, the actual application of a user or an IP for a period of time or a permanent time can only be counted access once, the subsequent access will not be counted into the total:
Public classHomecontroller:controller {Private ReadOnly Static stringKeyperfix ="Test_clicktotal_"; //Get:home Public AsyncTask<actionresult> Index (intId =0) { using(Connectionmultiplexer Redis = Connectionmultiplexer.connect ("localhost:6379") ) {Idatabase db= Redis. Getdatabase (4);//The redis default has 15 databases, and the parameters in Getdatabase () represent the data being stored in that data if(awaitDb. Keyexistsasync (Keyperfix + request.userhostaddress + Id) = =false)//The IP address of the keyperfix+ visitor is +id key, which records whether the IP has been clicked { //Description not found awaitDb. Stringincrementasync (Keyperfix + Id,1);//high efficiency by using Stringincrementasync for counting//This adds a record that has already been visited, the key value to be determined above the format consistent, value value is arbitrary, the third parameter indicates that the record will expire after one day awaitDb. Stringsetasync (Keyperfix + request.userhostaddress + Id,"true", Timespan.fromdays (1)); stringTotal =awaitDb. Stringgetasync (Keyperfix + Id);//added after reading outClicktotalmodel Totalmodel =NewClicktotalmodel {total =Convert.ToInt32 (total)}; returnView (Totalmodel); } Else { //read it directly. stringTotal =awaitDb. Stringgetasync (Keyperfix +Id); Clicktotalmodel Totalmodel=NewClicktotalmodel {total =Convert.ToInt32 (total)}; returnView (Totalmodel); } } } }
My implementation of this method is: through the IP to insert a key value of data, the effective time is one day, before counting the first to determine whether the IP record exists, if there is not counted into the total.
C # uses Redis to achieve site statistics access or the number of likes features!