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

本文详细介绍了如何使用jmemcached作为Java应用程序的缓存服务器,包括安装、配置和运行示例代码。通过设置缓存实例、启动服务以及与之交互的客户端代码,展示了如何有效地在Java应用中集成并利用缓存技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值