当前位置: 首页 > 工具软件 > jmemcached > 使用案例 >

jmemcached是采用Java实现的memcached服务器

西门梓
2023-12-01

jmemcached是采用Java实现的memcached服务器。它非常适合集成测试或嵌到Java应用程序中使用。

 

jmemcached缓存,客户端实例

1. 先下载:jmemcached & spymemcached


jmemcached-cli-0.8-main.jar & jmemcached-core-0.8.jar

http://code.google.com/p/jmemcache-daemon/downloads/list

spymemcached

memcached-2.5.jar

http://code.google.com/p/spymemcached/downloads/list


2. 运行:Server程序

import java.io.IOException;
import java.net.InetSocketAddress;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.MemCacheDaemon;
import com.thimbleware.jmemcached.storage.hash.LRUCacheStorageDelegate;

public class Server {
   public static void main(String s[]) {
       int maxItems = 1024;
       long maxBytes = 1024 * 2048;
       long ceilingSize = 2048;
       MemCacheDaemon daemon = new MemCacheDaemon();
       daemon.setAddr(new InetSocketAddress("localhost", 11211));
       LRUCacheStorageDelegate cacheStorage = new LRUCacheStorageDelegate(
               maxItems, maxBytes, ceilingSize);
       daemon.setCache(new Cache(cacheStorage));
       daemon.setBinary(false);
       try {
           daemon.start();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}



3. 运行Client程序

import java.io.IOException;
import java.net.InetSocketAddress;
import net.spy.memcached.MemcachedClient;

public class Client {
   public static void main(String s[]) {
       Client.setData("testdata");      //set data to MemCache
       String result = Client.getData();//get data to MemCache
       System.out.println(result);
   }

   public static void setData(String input) {
       MemcachedClient c = null;
       try {
           c = new MemcachedClient(new InetSocketAddress("localhost", 11211));
       } catch (IOException e) {
           e.printStackTrace();
       }
       // Store a value (async) for one hour(3600S)
       c.set("someKey", 3600, input);
       c.shutdown();
   }

   public static String getData() {
       String result = "";
       MemcachedClient c = null;
       try {
           c = new MemcachedClient(new InetSocketAddress("localhost", 11211));
       } catch (IOException e) {
           e.printStackTrace();
       }
       // Retrieve a value (synchronously).
       Object myObject = c.get("someKey");
       result = myObject.toString();
       c.shutdown();
       return result;
   }
}

 类似资料: