All Products
Search
Document Center

ApsaraDB for Memcache:Java_ Spymemcache

Last Updated:Aug 08, 2023

Download the client

Download address

About the client

Java example code

  1. Prepare the Java development environment. Log on to the Alibaba Cloud ECS server, and install the Java Development Kit (JDK) and commonly used integrated development environment (IDE) (such as Eclipse) on the server.

    Java JDK (Download address)

    Eclipse (Download address)

  2. The first example code is as follows. Copy the Java code in it into the Eclipse Project.

    Note

    Note: At this time, the code compilation will fail. A third-party JAR package download address is required to call the Memcache cache service. With this JAR package added, the code compilation will go through.

    OcsSample1.java example code (user name and password are required)

     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 OcsSample1 { 
    
          public static void main(String[] args) { 
    
                    final String host = "xxxxxxxx.m.yyyyyyyyyy.ocs.aliyuncs.com";//The "Intranet address" on the console
                    final String port ="11211"; //Default port 11211, no need to change
                    final String username = "xxxxxxxxx";//The "instance ID" in the console. The username of the new version of ApsaraDB for Memcache can be left blank.
                    final String password = "my_password";//The “password” provided in the email
                    MemcachedClient cache = null;
                    try {
                             AuthDescriptor ad = new AuthDescriptor(new String[]{"PLAIN"}, new PlainCallbackHandler(username, password));
    
                             cache = new MemcachedClient(
                                                new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
                                     .setAuthDescriptor(ad)
                                     .build(),
                                     AddrUtil.getAddresses(host + ":" + port));
    
                             System.out.println("ApsaraDB for Memcache Sample Code");
    
                             //Store a piece of data with the “ocs” key into the ApsaraDB for Memcache to facilitate subsequent data verification and reading.
                             String key = "ocs";
                             String value = "Open Cache Service,  from www.Aliyun.com";
                             int expireTime = 1000; // Expiration time, unit: second; starts timing from the data write. After the expireTime elapses, the data will become expired and won't be read;
                             OperationFuture<Boolean> future = cache.set(key, expireTime, value);
                             future.get();  // The spymemcached set() method is asynchronous. The future.get() waits for the cache.set() operation to complete. You can also choose not to wait based on your needs.
                             //Store several pieces of data into the ApsaraDB for Memcache and then you can see the statistics information on the ApsaraDB for Memcache console.
                             for(int i=0;i<100;i++){
                                    key="key-"+i;
                                    value="value-"+i;
    
                                    //Run the set operation and store data into the cache
                                    expireTime = 1000; // Expiration time, unit: seconds
                                    future = cache.set(key, expireTime, value);
                                    future.get();  //  Make sure the previous (cache.set()) operation has been completed
                             }
                             System.out.println("Set operation is completed.");
                                //Run the get operation and read data from the cache. Read data with the “ocs” key.
    
                             System.out.println("Get operation:"+cache.get(key));
    
                                    } catch (IOException e) {
                                           e.printStackTrace();
                                    } catch (InterruptedException e) {
                                           e.printStackTrace();
                                    } catch (ExecutionException e) {
                                           e.printStackTrace();
                                    }
                                    if (cache != null) {
                                           cache.shutdown();
                                    }
    
          }//eof    
     }

    OcsSample2.java example code (user name and password are not required)

     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 OcsSample2 {
    
     public static void main(String[] args) {
    
         final String host = "xxxxxxxx.m.yyyyyyyyyy.ocs.aliyuncs.com"; //The “intranet address” on the console
         final String port = "11211"; //Default port 11211, no need to change
    
         MemcachedClient cache = null;
         try {
    
             cache = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(host + ":" + port));
    
             System.out.println("OCS Sample Code");
    
             //Store a piece of data with the “ocs” key into the ApsaraDB for Memcache to facilitate subsequent data verification and reading.
             String key = "ocs";
             String value = "Open Cache Service,  from www.Aliyun.com";
             int expireTime = 1000; // Expiration time, unit: second; starts timing from the data write. After the expireTime elapses, the data will become expired and won't be read;
             OperationFuture<Boolean> future = cache.set(key, expireTime, value);
             future.get();
             //Store several pieces of data into the ApsaraDB for Memcache and then you can see the statistics information on the ApsaraDB for Memcache console.
             for (int i = 0; i < 100; i++) {
                 key = "key-" + i;
                 value = "value-" + i;
    
                 //Run the set operation and store data into the cache
                 expireTime = 1000; // expiration time,unit:second
                 future = cache.set(key, expireTime, value);
                 future.get();
             }
    
             System.out.println(”Set operation completed.");
    
             //Run the get operation and read data from the cache. Read data with the “ocs” key.
             System.out.println("Get operation:" + cache.get(key));
    
         } catch (IOException e) {
             e.printStackTrace();
         } catch (InterruptedException e) {
             e.printStackTrace();
         } catch (ExecutionException e) {
             e.printStackTrace();
         }
         if (cache != null) {
             cache.shutdown();
         }
    
     }//eof
     }
  3. Modify several items in OcsSample1.java in Eclipse according to your own instance information.

    The ApsaraDB for Memcache instance ID is unique and the Alibaba Cloud intranet address it corresponds to is also unique. All the information is displayed on the ApsaraDB for Memcache console. When establishing connections with your own ApsaraDB for Memcache instance, you must modify the corresponding information in OcsSample1.java based on the information.

  4. After the information is modified, you can run your own program. Run the main function, and you will see the following result in the console window within Eclipse (ignore the red INFO debugging information that may appear).

     OCS Sample Code
     Set operation is completed.
     Get operation: Open Cache Service, from www.Aliyun.com