Memcache Implementing a public counter Web site

Source: Internet
Author: User
Tags log log

The most recent item encountered during the anti-problem process. A lot of information on the Internet has not been fully realized.

So to find the Xmemcache client and memcache associated APIs and instructions that are right for you, we found a more perfect implementation.
Key class: Net.rubyeye.xmemcached.Counter
Related APIs

Implementation ideas:
Get:
Obtained by default from the Memcache, the initial fetch is not obtained, load the database to get the value, and initialize the value of the counter.


Update
The value of the counter is obtained from the Memcache first, and the value of the counter is initialized by loading the database without obtaining the obtained value.


Then add 1 to the counter and get the return value after the operation, assuming that the integer multiples of 100 are updated to the database
The following is the code for the key implementation class

 PackageCom.liu.memcache.tools;ImportJava.io.IOException;ImportNet.rubyeye.xmemcached.Counter;ImportNet.rubyeye.xmemcached.MemcachedClient;ImportNet.rubyeye.xmemcached.MemcachedClientBuilder;ImportNet.rubyeye.xmemcached.XMemcachedClientBuilder;ImportNet.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;ImportNet.rubyeye.xmemcached.utils.AddrUtil; Public  class memcachedtools {    Private Static FinalMemcachedtools instance =NewMemcachedtools ();/** * Instance * * @return  * *     Public StaticMemcachedtoolsgetinstance() {returnInstance }Private StaticString memcached_address = Configutil.getinstance (). GetString ("Memcached_address");Private StaticString memcached_head=configutil.getinstance (). GetString ("Memcached_head");/** * Value Added 1 * @param key * @return * /     Public Long Increasevalue(String key) {Longaddresult=0; String memkey=memcached_head+":"+MD5HEX.GETDIGESTMD5 (key);Try{Memcachedclientbuilder Builder =NewXmemcachedclientbuilder (Addrutil.getaddresses (memcached_address)); Builder.setsessionlocator (NewKetamamemcachedsessionlocator ());            Memcachedclient memcachedclient = Builder.build ();            Counter Counter=memcachedclient.getcounter (Memkey); Addresult=counter.incrementandget ();Try{//close memcached clientMemcachedclient.shutdown (); }Catch(IOException e) {System.err.println ("Shutdown memcachedclient fail");            E.printstacktrace (); }        }Catch(Exception ex) {Ex.printstacktrace ();//return ERROR;} System.out.println ("================"+addresult);returnAddresult; }/** * Initialize counter * @param key * @param DefaultValue */     Public void Initcounter(String Key,LongDefaultValue) {String memkey=memcached_head+":"+MD5HEX.GETDIGESTMD5 (key);Try{Memcachedclientbuilder Builder =NewXmemcachedclientbuilder (Addrutil.getaddresses (memcached_address)); Builder.setsessionlocator (NewKetamamemcachedsessionlocator ());            Memcachedclient memcachedclient = Builder.build ();            Counter Counter=memcachedclient.getcounter (Memkey,defaultvalue); Counter.set (defaultvalue);Try{//close memcached clientMemcachedclient.shutdown (); }Catch(IOException e) {System.err.println ("Shutdown memcachedclient fail");            E.printstacktrace (); }        }Catch(Exception ex) {Ex.printstacktrace ();//return ERROR;}    }/** * Gets the value of the counter * @param key * @return  */     Public Long Getcountervalue(String key) {String memkey=memcached_head+":"+MD5HEX.GETDIGESTMD5 (key);Longret=0;Try{Memcachedclientbuilder Builder =NewXmemcachedclientbuilder (Addrutil.getaddresses (memcached_address)); Builder.setsessionlocator (NewKetamamemcachedsessionlocator ());            Memcachedclient memcachedclient = Builder.build ();            Counter Counter=memcachedclient.getcounter (Memkey); Ret= Counter.get ();Try{//close memcached clientMemcachedclient.shutdown (); }Catch(IOException e) {System.err.println ("Shutdown memcachedclient fail");            E.printstacktrace (); }        }Catch(Exception ex) {Ex.printstacktrace ();//return ERROR;}returnRet }}

Action Counter Implementation class

 PackageCom.liu.counter;ImportOrg.apache.commons.logging.Log;ImportOrg.apache.commons.logging.LogFactory;ImportCom.liu.memcache.tools.MemCachedTools;/** * @author Chao.liu * @date 2015-03-06 * */ Public  class counterservice {    protectedLog log = Logfactory.getlog (GetClass ()); Public Long Getstatisticsdata() {String Memkey ="Count"; Long count =NULL;Try{count = (Long) memcachedtools.getinstance (). Getcountervalue (Memkey); }Catch(Exception e) {        }if(Count = =0) {Try{//TODO: Loading from database, omitted hereCount = -L }Catch(Exception e)        {} memcachedtools.getinstance (). Initcounter (Memkey, Count); }Else{//TODO: Output to foreground processingLog.info ("Statisticsservice.getstatisticsdata get data to memcached ... ....."); }returnCount }/** * UPDATE STATISTICS * * @param channelid * @param moduleid * @return */
          PublicStringUpdatestatisticsdata() {String Memkey ="Count"; String res ="1"; Long count =NULL;Try{count = (Long) memcachedtools.getinstance (). Getcountervalue (Memkey); }Catch(Exception e) {        }if(Count = =0) {//empty when loading from a database            //TODO: Loading from database, omitted hereCount = -L        Memcachedtools.getinstance (). Initcounter (Memkey, Count); }LongAddres = Memcachedtools.getinstance (). Increasevalue (Memkey);Try{if(Addres! =0) {if(Addres% -==0) {//per 100 updates to the database once                    //Update to DB operation}            }        }Catch(Exception e) {res ="0"; }returnRes } Public Static void Main(string[] args) {Counterservice ss=NewCounterservice (); System.out.println ("The current count number is:"+ss.getstatisticsdata ());        Ss.updatestatisticsdata (); System.out.println ("plus 1 , the number of counts is:"+ss.getstatisticsdata ()); }}

Execution effect:
The current number of counts is: 123
================124
Plus 1 The number of counts is: 124

Code Download:
http://download.csdn.net/detail/shanhuhau/8508929

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Memcache Implementing a public counter Web site

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.