Memcached-java Operation Memcached Instance

Source: Internet
Author: User
Tags delete key

The previous blog describes how to install memcached in the Windows operating system, summarizing how to use Java to manipulate memcached instances:

Code One:

Package Com.ghj.packageoftool;import Java.io.bufferedwriter;import Java.io.filewriter;import java.io.IOException; Import Java.io.printwriter;import Java.io.stringwriter;import Java.lang.management.managementfactory;import Java.text.simpledateformat;import Java.util.date;import Com.danga.memcached.memcachedclient;import com.danga.memcached.sockiopool;/** * MemCached Tool class * * @author Gaohuanjie */public class Memcachedutils {private static Me Mcachedclient memcachedclient;static {/************************************ configuration memcached**************************         /Sockiopool Sockiopool = Sockiopool.getinstance (); Sockiopool.setservers (New string[]{"127.0.0.1:11211"});//Set memcached server address Sockiopool.setweights (new integer[]{3}) ;  Set each memcached server weight sockiopool.setfailover (true);         Whether to connect to another memcached server when a memcached server fails.    Sockiopool.setinitconn (10);     Number of connections established for each server at initialization sockiopool.setminconn (10); Establish the minimum number of connections per server SockiopOol.setmaxconn (100);  Establish maximum number of connections per server Sockiopool.setmaintsleep (30);    Self-examination thread cycle to work, the time of each sleep Sockiopool.setnagle (false); The socket parameter, if true, is not buffered when writing the data and is immediately sent out.         The rule of TCP is that before a packet is sent, the sender of the package waits for the remote receiver to confirm that it has received the last packet sent, and this method closes the socket cache-the packet is ready to be sent out immediately.  Sockiopool.setsocketto (3000); The socket block reads the data timeout Sockiopool.setalivecheck (true);//sets whether to check whether the memcached server is invalid Sockiopool.setmaxidle (1000*30* 30);  Set maximum processing time Sockiopool.setsocketconnectto (0);  Control of timeout when connection is established sockiopool.initialize ();         Initialize the connection pool if (memcachedclient = = null) {memcachedclient = new memcachedclient (); Memcachedclient.setprimitiveasstring (TRUE);//Whether the base type is converted to the string method}}private Memcachedutils () {}/** * Adds a key-value pair to the cache. Note: If the key already exists, the value corresponding to the previous key will be replaced. * * @author Gaohuanjie */public Static Boolean set (String key, Object value) {try {return Memcachedclient.set (key, value) ;} catch (Exception e) {memcachedlogutils.writelog ("Memcached set method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); Return false;}} /** * Adds a key-value pair to the cache and sets a time-out for that key-value pair (that is, how long the key-value pair is removed from the memcached memory cache, such as: New Date (1000*10), which is removed from the memcached memory cache after 10 seconds). Note: If the key already exists, the value corresponding to the previous key will be replaced. * * @author Gaohuanjie */public Static Boolean set (String key, Object value, Date expire) {try {return memcachedclient.se T (key, value, expire);} catch (Exception e) {memcachedlogutils.writelog ("Memcached set method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return Fals e;}} /** * Adds a key-value pair to the cache. Note: Success is only added if the key does not exist in the cache. * * @author Gaohuanjie */public Static Boolean Add (String key, Object value) {try {if (get (key) = null) {Memcachedloguti Ls.writelog ("Memcached Add method Error, Key value:" + key + "\ r \ n" + exceptionwrite ("The key value pair already exists in the Memcached Memory Cache")); return false;} Else{return Memcachedclient.add (key, value);}} catch (Exception e) {memcachedlogutils.writelog ("Memcached Add method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return Fals e;}} /** * Adds a key-value pair to the cache and sets a time-out for that key-value pair (that is, how long the key-value pair is removed from the memcached memory cache, such as: New Date (1000*10), which is removed from the memcached memory cache after 10 seconds). Note: Success is only added if the key does not exist in the cache. * * @aUthor Gaohuanjie */public Static Boolean Add (String key, Object value, Date expire) {try {if (get (key) = null) {Memcached Logutils.writelog ("Memcached Add method Error, Key value:" + key + "\ r \ n" + exceptionwrite ("The key value pair already exists in the Memcached Memory Cache")); return false;} Else{return Memcachedclient.add (key, value, expire);}} catch (Exception e) {memcachedlogutils.writelog ("Memcached Add method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return Fals e;}} /** * replaces the corresponding values that are already in the memcached memory cache by key. Note: The corresponding value of the key is replaced only if the key exists. * * @author Gaohuanjie */public Static Boolean replace (String key, Object newvalue) {try {return memcachedclient.replace ( Key, NewValue);} catch (Exception e) {memcachedlogutils.writelog ("Memcached replace method error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return false;}} /** * replaces the corresponding value in the memcached memory cache with the key and sets the elapsed time (that is, how long the key value pair is removed from the memcached memory cache, such as: New Date (1000*10), is removed from the memcached memory cache after 10 seconds). Note: The corresponding value of the key is replaced only if the key exists. * * @author Gaohuanjie */public Static Boolean replace (String key, Object newvalue, Date expiredate) {try {return Memcachedclient.replace (key, NewValue, ExpireDate),} catch (Exception e) {Memcachedlogutils.writelog (" Memcached Replace method Error, Key value: "+ key +" \ r \ n "+ exceptionwrite (e)); return false;}} /** * The corresponding value in the memcached memory cache management system according to the key * * @author Gaohuanjie */public static Object get (String key) {try {return memcachedcli Ent.get (key);} catch (Exception e) {memcachedlogutils.writelog ("Memcached get method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return null ;}} /** * Delete key/value pairs in memcached by key * * @author Gaohuanjie */public Static Boolean delete (String key) {try {return memcachedclient . Delete (key);} catch (Exception e) {memcachedlogutils.writelog ("Memcached Delete method Error, Key value:" + key + "\ r \ n" + exceptionwrite (e)); return F Alse;}}  /** * Delete key/value pairs in memcached * * @author Gaohuanjie */public Static Boolean Delete (String) based on key and overdue time (e.g. new date (1000*10): 10 seconds expired) Key, Date expiredate) {try {return Memcachedclient.delete (key, expiredate);} catch (Exception e) {Memcachedlogutils.writ ELog ("Memcached Delete method Error, Key value:" + KEY + "\ r \ n" + exceptionwrite (e)); return false;}} /** * Clears all key/value pairs in the cache * * @author Gaohuanjie */public static Boolean Flashall () {try {return memcachedclient.flushall ();} CA TCH (Exception e) {memcachedlogutils.writelog ("Memcached Flashall method error \ r \ n" + exceptionwrite (e)); return false;}} /** * Returns exception stack information for String type * * @author Gaohuanjie */private static string Exceptionwrite (Exception Exception) {StringWriter s Tringwriter = new StringWriter (); PrintWriter printwriter = new PrintWriter (StringWriter), Exception.printstacktrace (PrintWriter);p Rintwriter.flush () ; return stringwriter.tostring ();} /** * memcached Logging Tool * * @author Gaohuanjie */private static class Memcachedlogutils {private static FileWriter Filewrit Er;private static BufferedWriter logwrite;private final static String PID = Managementfactory.getruntimemxbean (). GetName ();//Get pid/** * Initialize memcached log write stream by locating the corresponding JVM process * * @author Gaohuanjie */static {try {String osname = System.getpro Perty ("Os.name"), if (Osname.contains ("Windows")) {FileWriter = new FileWriter ("D:\\memcached.log", True);} else {fileWriter = new FileWriter ("/usr/local/logs/memcached.log", True);} Logwrite = new BufferedWriter (fileWriter);} catch (IOException IOException) {ioexception.printstacktrace (); try {if (fileWriter! = null) {Filewriter.close ();} if (logwrite! = null) {Logwrite.close ();}} catch (Exception Exception) {exception.printstacktrace ();}}} /** * Write Log information * * @author Gaohuanjie */public static void Writelog (String logcontent) {try {logwrite.write ("[" + PID + "] "+"-["+ New SimpleDateFormat (" Yyyy-mm-dd HH:mm:ss "). Format (new Date ()) +"]\r\n "+ logcontent); Logwrite.newline (); LOGW Rite.flush ();} catch (IOException e) {e.printstacktrace ();}}}}

Code two:

Package Com.ghj.packageofclient;import Java.util.date;import Junit.framework.testcase;import Com.ghj.packageoftool.memcachedutils;public class Client extends testcase{/** * Tests the Set method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestSet1 () {Memcachedutils.set ("set1description", "Call the Memcachedutils class's set method, There is no setting of the duration of the key-value pair "); System.out.println (Memcachedutils.get ("Set1description"). toString ());} /** * Test the Set method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestSet2 () {Memcachedutils.set ("set2description", "Call the Memcachedutils class's set method, Set the existence time of the key-value pair-existence 60 seconds ", New Date (1000*60)); System.out.println (Memcachedutils.get ("Set2description"). toString ());} /** * Test the Add method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestAdd1 () {Memcachedutils.add ("add1description", "Call the Memcachedutils class's Add method, There is no setting of the duration of the key-value pair "); System.out.println (Memcachedutils.get ("Add1description"). toString ());} /** * Test the Add method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestAdd2 () {MemcachedutiLs.add ("Add2description", "call the Add method of the Memcachedutils class, set the existence duration of the key-value pair-exists 60 seconds", New Date (1000*60)); System.out.println (Memcachedutils.get ("Add2description"). toString ());} /** * Test the Replace method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestReplace1 () {Memcachedutils.add ("replace1description", " Call the Replace method of the Memcachedutils class without setting the duration of the key-value pair "); Memcachedutils.replace ("Replace1description", "VALUE changed!!!" "); System.out.println (Memcachedutils.get ("Replace1description"). toString ());} /** * Test the Replace method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestReplace2 () {Memcachedutils.add ("replace2description", " Call the Replace method of the Memcachedutils class, set the existence time of the key-value pair-exists 60 seconds ", New Date (1000*60)); Memcachedutils.replace ("Replace2description", "VALUE changed!!!" ", New Date (1000*60)); System.out.println (Memcachedutils.get ("Replace2description"). toString ());} /** * Test The Get method of the Memcachedutils class. * * @author Gaohuanjie */public static void Testget () {Memcachedutils.add ("getdescription", "Call Memcachedutils class's Get method, There is no setting of the duration of the key-value pair "); SysteM.out.println (Memcachedutils.get ("GetDescription"). toString ());} /** * Test the Delete method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestDelete1 () {Memcachedutils.add ("delete1description", " Call the Delete method of the Memcachedutils class without setting the time period for the key value pair "); Memcachedutils.delete ("Delete1description"); Assertequals (null, Memcachedutils.get ("delete1description"));} /** * Test the Delete method of the Memcachedutils class. * * @author Gaohuanjie */public static void TestDelete2 () {Memcachedutils.set ("Delete2description1", " Call the Delete method of the Memcachedutils class, set the time period for the key-value pair ", New Date (600*1000)); Memcachedutils.delete ("Delete2description1", New Date (1000*600)), assertequals (null, Memcachedutils.get (" Delete2description1 "));} /** * Test the Flashall method of the Memcachedutils class. * * @author Gaohuanjie */public static void Testflashall () {Memcachedutils.add ("flashalldescription", " Call the Delete method of the Memcachedutils class without setting the expected duration of the key-value pair "); Memcachedutils.flashall (); Assertequals (null, Memcachedutils.get ("flashalldescription"));}}
Summarize:

1, above is a complete example, because the memcached example needs to rely on a specific jar package, so the direct copy does not run, "0-minute Download full demo"

2. Although the memcached operation was implemented using the Java programming language, the Delete (String key, Date expiredate) seems to be less useful in the Windows operating system- The data in the memcached cache can be deleted according to key, but the later parameter of overdue time will not work at all, look for the twos.

Memcached-java Operation Memcached Instance

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.