[This article is from the Sky Cloud-owned blog Park]
Preparatory work
Java operations Memcache requires support for Spymemcache class libraries to modify the Pom.xml file for MAVEN projects in eclipse--
To add a warehouse:
<repositories> <Repository> <ID>Spy</ID> <name>Spy Repository</name> <Layout>Default</Layout> <URL>http://files.couchbase.com/maven2/</URL> <Snapshots> <enabled>False</enabled> </Snapshots> </Repository> </repositories>
Add Dependencies:
<Dependency> <groupId>Spy</groupId> <Artifactid>Spymemcached</Artifactid> <version>2.6</version> <Scope>Provided</Scope> </Dependency>
Once added, MAVEN will automatically download the appropriate class library as well.
Operation method
To create a new tool class Memcachetool.java, the method code for manipulating Memcache is as follows:
PackageUtils;Importjava.io.IOException;Importjava.net.InetSocketAddress;Importnet.spy.memcached.MemcachedClient; Public classMemcachetool {Privatememcachedclient mclient; Publicmemcachedclient getmclient () {returnmclient; } Public voidsetmclient (memcachedclient mclient) { This. mclient =mclient; } PublicMemcachetool (String IP,intPort) { Try{setmclient (NewMemcachedclient (Newinetsocketaddress (IP, port)); } Catch(IOException e) {e.printstacktrace (); } } Public voidSetkey (String keyName, String keyValue) {Mclient.set (KeyName,3600, KeyValue); } Publicstring GetKey (String keyName) {returnMclient.get (keyName). toString (); } Public Static voidMain (string[] args)throwsioexception {String IP= "Xx.xxx.xxx.xxx"; intPort = xxxxx; Memcachetool Memcachetool=Newmemcachetool (IP, port); String KeyName= "XXXX"; System.out.println (Memcachetool.getkey (keyName)); String KeyValue= "XXXX"; Memcachetool.setkey (KeyName, KeyValue); System.out.println (Memcachetool.getkey (keyName)); }}
where x is missing the part to replace:
IP: Fill in the IP address of the server where the memcache resides;
Port: Enter the port number to access the Memcache server;
KeyName: The name of the key to be modified or acquired;
KeyValue: The key value to be modified.
Java Operation Memcache