Updated on 2024-07-29 GMT+08:00

Connecting to Memcached on the Spymemcached (Java)

Access a DCS Memcached instance using a Java client on an ECS in the same VPC.

Prerequisites

  • The DCS Memcached instance you want to access is in the Running state.
  • An ECS has been created on which the client has been installed. For details on how to create ECSs, see the Elastic Cloud Server User Guide.

    An ECS can communicate with a DCS instance that belongs to the same VPC and is configured with the same security group.

    • If the ECS and DCS instance are not in the same VPC, you can establish a VPC peering connection to achieve network connectivity between the ECS and DCS instance. For details, see Does DCS Support Cross-VPC Access?
    • If different security groups have been configured for the ECS and DCS instance, you can set security group rules to achieve network connectivity between the ECS and DCS instance. For details, see Security Group Configurations.
  • The Java development kit (JDK) and common integrated development environments (IDEs) such as Eclipse have been installed on the ECS.
  • You have obtained the spymemcached-x.y.z.jar dependency package.

    x.y.z indicates the version of the dependency package. The latest version is recommended.

Connecting to Memcached on the Spymemcached

  1. Log in to the DCS console.
  2. Click in the upper left corner of the management console and select the region where your instance is located.
  3. In the navigation pane, choose Cache Manager.
  4. On the Cache Manager page, click the name of the DCS Memcached instance you want to access. Obtain the IP address and port number of the instance.
  5. Upload the obtained spymemcached-x.y.z.jar dependency package to the created ECS.
  6. Log in to the ECS.
  7. Create a Java project on Eclipse and import the spymemcached-x.y.z.jar dependency package. The project name is customizable.
  8. Create a ConnectMemcached1 class, copy the following Java code to the class, and modify the code.

    • Example code for the password mode

      Change ip:port to the IP address and port number obtained in 4. Set userName and password respectively to the username and password of the Memcached instance.

      //Connect to the encrypted Memcached code using Java.
      import java.io.IOException;
      import java.util.concurrent.ExecutionException;
      
      import net.spy.memcached.AddrUtil;
      import net.spy.memcached.ConnectionFactoryBuilder;
      import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
      import net.spy.memcached.MemcachedClient;
      import net.spy.memcached.auth.AuthDescriptor;
      import net.spy.memcached.auth.PlainCallbackHandler;
      import net.spy.memcached.internal.OperationFuture;
      
      public class ConnectMemcached1
      {
          public static void main(String[] args)
          {
              final String connectionaddress = "ip:port"; 
              final String username = "userName";//Indicates the username.
              final String password = "password";//Indicates the password.
              MemcachedClient client = null;
              try
              {
                  AuthDescriptor authDescriptor =
                      new AuthDescriptor(new String[] {"PLAIN"}, new PlainCallbackHandler(username,
                              password));
                  client = new MemcachedClient(
                          new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
                                  .setAuthDescriptor(authDescriptor)
                                  .build(),
                          AddrUtil.getAddresses(connectionaddress));
                  String key = "memcached";//Stores data with the key being memcached in Memcached.
                  String value = "Hello World";//The value is Hello World. 
                  int expireTime = 5; //Specifies the expiration time, measured in seconds. The countdown starts from the moment data is written. After the expireTime elapses, the data expires and can no longer be read.
                  doExcute(client, key, value, expireTime);//Executes the operation.
              }
              catch (IOException e)
              {
                  e.printStackTrace();
              }
          }
      
          /**
           *Method of writing data to Memcached
           */
          private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
          {
              try
              {
                  OperationFuture<Boolean> future = client.set(key, expireTime, value);
                  future.get();//spymemcached set () is asynchronous. future.get () waits until the cache.set () operation is completed, or does not need to wait. You can select based on actual requirements.
                  System.out.println("The Set operation succeeded.");
                  System.out.println("Get operation:" + client.get(key));
                  Thread.sleep(6000);//Waits for 6000 ms, that is, 6s. Then the data expires and can no longer be read.
                  System.out.println("Perform the Get operation 6s later:" + client.get(key));
      
              }
              catch (InterruptedException e)
              {
                  e.printStackTrace();
              }
              catch (ExecutionException e)
              {
                  e.printStackTrace();
              }
              if (client != null)
              {
                  client.shutdown();
              }
          }
      }
    • Example code for the password-free mode

      Change ip:port to the IP address and port number obtained in 4.

      //Connect to the password-free Memcached code using Java.
      import java.io.IOException;
      import java.util.concurrent.ExecutionException;
      
      import net.spy.memcached.AddrUtil;
      import net.spy.memcached.BinaryConnectionFactory;
      import net.spy.memcached.MemcachedClient;
      import net.spy.memcached.internal.OperationFuture;
      
      public class ConnectMemcached
      {
          public static void main(String[] args)
          {
              final String connectionaddress = "ip:port"; 
              MemcachedClient client = null;
              try
              {
                  client = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(connectionaddress));
                  String key = "memcached";//Stores data with the key being memcached in Memcached.
                  String value = "Hello World";//The value is Hello World. 
                  int expireTime = 5; //Specifies the expiration time, measured in seconds. The countdown starts from the moment data is written. After the expireTime elapses, the data expires and can no longer be read.
                  doExcute(client, key, value, expireTime);//Executes the operation.
              }
              catch (IOException e)
              {
                  e.printStackTrace();
              }
          }
      
          /**
           *Method of writing data to Memcached
           */
          private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
          {
              try
              {
                  OperationFuture<Boolean> future = client.set(key, expireTime, value);
                  future.get();//spymemcached set () is asynchronous. future.get () waits until the cache.set () operation is completed, or does not need to wait. You can select based on actual requirements.
                  System.out.println("The Set operation succeeded.");
                  System.out.println("Get operation:" + client.get(key));
                  Thread.sleep(6000);//Waits for 6000 ms, that is, 6s. Then the data expires and can no longer be read.
                  System.out.println("Perform the Get operation 6s later:" + client.get(key));
      
              }
              catch (InterruptedException e)
              {
                  e.printStackTrace();
              }
              catch (ExecutionException e)
              {
                  e.printStackTrace();
              }
              if (client != null)
              {
                  client.shutdown();
              }
          }
      }

  9. Run the main method. The following result is displayed in the Console window of Eclipse:

    The Set operation succeeded.
    Get operation: Hello World
    Perform the Get operation 6s later: null