Using Java to operate Memcached
Using Java to operate Memcached requires the introduction of corresponding Java client libraries. It is recommended to use the spymemcached library for Memcached operations.
Firstly, add the dependency of spymemcached in the Maven project:
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
Next, you can use the following code snippet to demonstrate how to use Java to operate Memcached.
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClientIF;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
public class MemcachedExample {
public static void main(String[] args) {
try {
//Connect to Memcached server
MemcachedClientIF memcachedClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
//Add data to cache
Future<Boolean>setResult=memcachedClient. set ("key", 60, "value")// Validity period: 60 seconds
if (setResult.get()) {
System. out. println ("Data insertion successful");
}
//Get cached data
Object getResult = memcachedClient.get("key");
System. out. println ("Obtained data:"+getResult);
//Modify cache data
Future<Boolean> updateResult = memcachedClient.replace("key", 60, "new value");
if (updateResult.get()) {
System. out. println ("Data modified successfully");
}
//Delete cached data
Future<Boolean> deleteResult = memcachedClient.delete("key");
if (deleteResult.get()) {
System. out. println ("Data deleted successfully");
}
//Close Connection
memcachedClient.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the above code, first create a MemcachedClient instance and connect using the IP address and port number of the Memcached server. Then, you can use the 'set' method to add the data to the cache, use the 'get' method to obtain the cache data, use the 'replace' method to modify the cache data, and use the 'delete' method to delete the cache data. Finally, use the 'shutdown' method to close the connection to the Memcached server.
This is a simple Java code example used to demonstrate how to use the Java operation Memcached for data insertion, modification, query, and deletion. According to actual needs, corresponding modifications and extensions can be made based on this example.