Java_ Spymemcache

Download the client

Java example code

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.

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

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.

//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

}

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.

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).