导航:首页 > 编程语言 > javamemcached客户端

javamemcached客户端

发布时间:2022-05-27 16:26:19

A. 如何在javaweb中使用memcached

一、 概念

Memcached是danga.com(运营LiveJournal的技术团队)开发的一套分布式内存对象缓存系统,用于在动态系统中减少数据库负载,提升性能。

二、 适用场合

1. 分布式应用。由于memcached本身基于分布式的系统,所以尤其适合大型的分布式系统。

2. 数据库前段缓存。数据库常常是网站系统的瓶颈。数据库的大并发量访问,常常造成网站内存溢出。当然我们也可以使用hibernate的缓存机制。但memcached是基于分布式的,并可独立于网站应用本身,所以更适合大型网站进行应用的拆分。

3. 服务器间数据共享。举例来讲,我们将网站的登录系统、查询系统拆分为两个应用,放在不同的服务器上,并进行集群,那这个时候用户登录后,登录信息如何从登录系统服务器同步到查询系统服务器呢?这时候,我们便可以使用memcached,登录系统将登录信息缓存起来,查询系统便可以获得登录信息,就像获取本地信息一样。

4.代码如下:

package com.demo.memcached;
importJava.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemCached {
private static MemCachedClient cachedClient = new MemCachedClient(); // memcached客户端单例
/**
* 初始化连接池
*/
static {
System.out.println("初始化连接池");
// 获取连接池的实例
SockIOPool pool = SockIOPool.getInstance();
// 服务器列表及其权重
String[] servers = { "172.20.0.196:11211"};
Integer[] weights = { 3 };
// 设置服务器信息
pool.setServers(servers);
pool.setWeights(weights);
// 设置初始连接数、最小连接数、最大连接数、最大处理时间
pool.setInitConn(10);
pool.setMinConn(10);
pool.setMaxConn(1000);
// pool.setMaxIdle(1000 * 60 * 60);
pool.setMaxIdle(1000 * 60 * 60);
//设置主线程睡眠时间,每3秒苏醒一次,维持连接池大小
//maintSleep 千万不要设置成30,访问量一大就出问题,单位是毫秒,推荐30000毫秒。
pool.setMaintSleep(30000);
//关闭套接字缓存
pool.setNagle(false);
//连接建立后的超时时间
pool.setSocketTO(3000);
//连接建立时的超时时间
pool.setSocketConnectTO(0);
// 初始化并启动连接池
pool.initialize();
// 压缩设置,超过指定大小的都压缩
// cachedClient.setCompressEnable(true);
// cachedClient.setCompressThreshold(1024*1024);
}
public static boolean add(String key, Object value) {
return cachedClient.add(key, value);
}
/**
* 新增缓存数据,该KEY值如果没有则插入
* @param key
* 键(key)
* @param value
* @param expire
* 过期时间(单位是秒)
*
* @return
*/
public static boolean add(String key, Object value, Integer expire) {
return cachedClient.add(key, value, expire);
}
public static boolean add(String key, Object value, Date expireDate) {
return cachedClient.add(key, value, expireDate);
}
public static boolean set(String key, Object value) {
return cachedClient.set(key, value);
}
/**
* 设置缓存中的对象(value),如果没有则插入,如果有则修改。
* @param key
* @param value
* @param expire
* @return
*/
public static boolean set(String key, Object value, Integer expire) {
return cachedClient.set(key, value, expire);
}
/**
*
* @param key
* @param value
* @param expireDate
* 失效日期
* @return
*/
public static boolean set(String key, Object value, Date expireDate) {
return cachedClient.set(key, value, expireDate);
}
public static boolean replace(String key, Object value) {
return cachedClient.replace(key, value);
}
/**
* 该键的新值(new value),如果有则修改。
* @param key
* @param value
* @param expire
* @return
*/
public static boolean replace(String key, Object value, Integer expire) {
return cachedClient.replace(key, value, expire);
}
public static boolean replace(String key, Object value, Date expireDate) {
return cachedClient.replace(key, value, expireDate);
}
public static Object get(String key) {
return cachedClient.get(key);
}
/**
* 清空所有对象
*/
public static void flushAll(){
cachedClient.flushAll();
}
}



public class MemcachedTest {


public static void main(String[] agr){

// MemCached.set("mem", "12e3232", 1);
// MemCached.set("mem1", "mem1mem1");
// Date date=new Date(4000);
// MemCached.set("mem", "12e3232", date);
try{
// Thread.sleep(3000);
String mem=(String)MemCached.get("mem");
System.out.println("mem="+mem);
}catch(Exception ex){
ex.printStackTrace();
}
}
}

B. Memcached 在 Spring 里怎么用

本文将对在Java环境下Memcached应用进行详细介绍。Memcached主要是集群环境下的缓存解决方案,可以运行在Java或者.NET平台上,这里我们主要讲的是Windows下的Memcached应用。

这些天在设计SNA的架构,接触了一些远程缓存、集群、session复制等的东西,以前做企业应用的时候感觉作用不大,现在设计面对internet的系统架构时就非常有用了,而且在调试后看到压力测试的情况还是比较好的。

在缓存的选择上有过很多的思考,虽然说memcached结合java在序列化上性能不怎么样,不过也没有更好的集群环境下的缓存解决方案了,就选择了memcached。本来计划等公司买的服务器到位装个linux再来研究memcached,但这两天在找到了一个windows下的Memcached版本,就动手开始调整现有的框架了。

Windows下的Server端很简单,不用安装,双击运行后默认服务端口是11211,没有试着去更改端口,因为反正以后会用Unix版本,到时再记录安装步骤。下载客户端的JavaAPI包,接口非常简单,参考API手册上就有现成的例子。

目标,对旧框架缓存部分进行改造:

1、缓存工具类

2、hibernate的provider

3、用缓存实现session机制

今天先研究研究缓存工具类的改造,在旧框架中部分函数用了ehcache对执行结果进行了缓存处理,现在目标是提供一个缓存工具类,在配置文件中配置使用哪种缓存(memcached或ehcached),使其它程序对具体的缓存不依赖,同时使用AOP方式来对方法执行结果进行缓存。

首先是工具类的实现:

在Spring中配置
Java代码

<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xmlvalue>
property>
bean>

<bean id="localCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××.cache.LOCAL_CACHE" />
bean>

<bean id="cacheService"
class="×××.core.cache.CacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cache.servers}"/>
<property name="cacheServerWeights" value="${cache.cacheServerWeights}"/>
<property name="cacheCluster" value="${cache.cluster}"/>
<property name="localCache" ref="localCache"/>
bean>

<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xmlvalue>
property>
bean>
<bean id="localCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××.cache.LOCAL_CACHE" />
bean>

<bean id="cacheService"
class="×××.core.cache.CacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cache.servers}"/>
<property name="cacheServerWeights" value="${cache.cacheServerWeights}"/>
<property name="cacheCluster" value="${cache.cluster}"/>
<property name="localCache" ref="localCache"/>
bean>
在properties文件中配置${cache.servers} ${cache.cacheServerWeights} ${cache.cluster}

具体工具类的代码

Java代码
/**
* @author Marc
*
*/
public class CacheService {
private Log logger = LogFactory.getLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 * 60 * 30; // 30 minutes
long maxBusyTime = 1000 * 60 * 5; // 5 minutes
long maintThreadSleep = 1000 * 5; // 5 seconds
int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
int socketConnectTO = 1000 * 3; // 3 seconds to block on initial
// connections. If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService(){
mc = new MemCachedClient();
mc.setCompressEnable(false);
}
/**
* 放入
*
*/
public void put(String key, Object obj) {
Assert.hasText(key);
Assert.notNull(obj);
Assert.notNull(localCache);
if (this.cacheCluster) {
mc.set(key, obj);
} else {
Element element = new Element(key, (Serializable) obj);
localCache.put(element);
}
}
/**
* 删除
*/
public void remove(String key){
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) {
mc.delete(key);
}else{
localCache.remove(key);
}
}
/**
* 得到
*/
public Object get(String key) {
Assert.hasText(key);
Assert.notNull(localCache);
Object rt = null;
if (this.cacheCluster) {
rt = mc.get(key);
} else {
Element element = null;
try {
element = localCache.get(key);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: "
+ cacheException.getMessage());
}
if(element != null)
rt = element.getValue();
}
return rt;
}
/**
* 判断是否存在
*
*/
public boolean exist(String key){
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) {
return mc.keyExists(key);
}else{
return this.localCache.isKeyInCache(key);
}
}
private void init() {
if (this.cacheCluster) {
String[] serverlist = cacheServerList.split(",");
Integer[] weights = this.split(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(serverlist);
pool.setWeights(weights);
pool.setInitConn(initialConnections);
pool.setMinConn(minSpareConnections);
pool.setMaxConn(maxSpareConnections);
pool.setMaxIdle(maxIdleTime);
pool.setMaxBusyTime(maxBusyTime);
pool.setMaintSleep(maintThreadSleep);
pool.setSocketTO(socketTimeOut);
pool.setSocketConnectTO(socketConnectTO);
pool.setNagle(nagleAlg);
pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
pool.initialize();
logger.info("初始化memcached pool!");
}
}

private void destory() {
if (this.cacheCluster) {
SockIOPool.getInstance().shutDown();
}
}
}
/**
* @author Marc
*
*/
public class CacheService {
private Log logger = LogFactory.getLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 * 60 * 30; // 30 minutes
long maxBusyTime = 1000 * 60 * 5; // 5 minutes
long maintThreadSleep = 1000 * 5; // 5 seconds
int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
int socketConnectTO = 1000 * 3; // 3 seconds to block on initial
// connections. If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService(){
mc = new MemCachedClient();
mc.setCompressEnable(false);
}
/**
* 放入
*
*/
public void put(String key, Object obj) {
Assert.hasText(key);
Assert.notNull(obj);
Assert.notNull(localCache);
if (this.cacheCluster) {
mc.set(key, obj);
} else {
Element element = new Element(key, (Serializable) obj);
localCache.put(element);
}
}
/**
* 删除
*/
public void remove(String key){
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) {
mc.delete(key);
}else{
localCache.remove(key);
}
}
/**
* 得到
*/
public Object get(String key) {
Assert.hasText(key);
Assert.notNull(localCache);
Object rt = null;
if (this.cacheCluster) {
rt = mc.get(key);
} else {
Element element = null;
try {
element = localCache.get(key);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: "
+ cacheException.getMessage());
}
if(element != null)
rt = element.getValue();
}
return rt;
}
/**
* 判断是否存在
*
*/
public boolean exist(String key){
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) {
return mc.keyExists(key);
}else{
return this.localCache.isKeyInCache(key);
}
}
private void init() {
if (this.cacheCluster) {
String[] serverlist = cacheServerList.split(",");
Integer[] weights = this.split(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(serverlist);
pool.setWeights(weights);
pool.setInitConn(initialConnections);
pool.setMinConn(minSpareConnections);
pool.setMaxConn(maxSpareConnections);
pool.setMaxIdle(maxIdleTime);
pool.setMaxBusyTime(maxBusyTime);
pool.setMaintSleep(maintThreadSleep);
pool.setSocketTO(socketTimeOut);
pool.setSocketConnectTO(socketConnectTO);
pool.setNagle(nagleAlg);
pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
pool.initialize();
logger.info("初始化memcachedpool!");
}
}
private void destory() {
if (this.cacheCluster) {
SockIOPool.getInstance().shutDown();
}
}
}
然后实现函数的AOP拦截类,用来在函数执行前返回缓存内容

Java代码
public class CachingInterceptor implements MethodInterceptor {

private CacheService cacheService;
private String cacheKey;

public void setCacheKey(String cacheKey) {
this.cacheKey = cacheKey;
}

public void setCacheService(CacheService cacheService) {
this.cacheService = cacheService;
}

public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = cacheService.get(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) {
result = invocation.proceed();
cacheService.put(cacheKey,result);
}
return result;
}
}
public class CachingInterceptor implements MethodInterceptor {

private CacheService cacheService;
private String cacheKey;

public void setCacheKey(String cacheKey) {
this.cacheKey = cacheKey;
}

public void setCacheService(CacheService cacheService) {
this.cacheService = cacheService;
}

public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = cacheService.get(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) {
result = invocation.proceed();
cacheService.put(cacheKey,result);
}
return result;
}
}
Spring的AOP配置如下:

Java代码

<aop:config proxy-target-class="true">
<aop:advisor
pointcut="execution(* ×××.PoiService.getOne(..))"
advice-ref="PoiServiceCachingAdvice" />
aop:config>

<bean id="BasPoiServiceCachingAdvice"
class="×××.core.cache.CachingInterceptor">
<property name="cacheKey" value="PoiService" />
<property name="cacheService" ref="cacheService" />
bean>
转载

C. 如何配置Memcached服务器

Windows下的Memcache安装
1. 下载memcache的windows稳定版,解压放某个盘下面,比如在c:\memcached
2. 在终端(也即cmd命令界面)下输入 c:\memcached\memcached.exe -d install --安装memcached成为服务,这样才能正常运行,否则运行失败!

3. 再输入: c:\memcached\memcached.exe -d start --启动memcached的。

以后memcached将作为windows的一个服务每次开机时自动启动。这样服务器端已经安装完毕了。

Linux下的安装:
1.下载memcached和libevent,放到 /tmp 目录下
# cd /tmp
# wget http://www.danga.com/memcached/dist/memcached-1.2.0.tar.gz
# wget http://www.monkey.org/~provos/libevent-1.2.tar.gz
2.先安装libevent:
# tar zxvf libevent-1.2.tar.gz
# cd libevent-1.2
# ./configure –prefix=/usr
# make
# make install
3.测试libevent是否安装成功:
# ls -al /usr/lib | grep libevent
lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent-1.2.so.1 -> libevent-1.2.so.1.0.3
-rwxr-xr-x 1 root root 263546 11?? 12 17:38 libevent-1.2.so.1.0.3
-rw-r–r– 1 root root 454156 11?? 12 17:38 libevent.a
-rwxr-xr-x 1 root root 811 11?? 12 17:38 libevent.la
lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent.so -> libevent-1.2.so.1.0.3

4.安装memcached,同时需要安装中指定libevent的安装位置:
# cd /tmp
# tar zxvf memcached-1.2.0.tar.gz
# cd memcached-1.2.0
# ./configure –with-libevent=/usr
# make
# make install
如果中间出现报错,请仔细检查错误信息,按照错误信息来配置或者增加相应的库或者路径。
安装完成后会把memcached放到 /usr/local/bin/memcached ,
5.测试是否成功安装memcached:
# ls -al /usr/local/bin/mem*
-rwxr-xr-x 1 root root 137986 11?? 12 17:39 /usr/local/bin/memcached
-rwxr-xr-x 1 root root 140179 11?? 12 17:39 /usr/local/bin/memcached-debug

memcached的基本设置:
1.启动Memcache的服务器端:
# /usr/local/bin/memcached -d -m 10 -u root -l 192.168.0.200 -p 12000 -c 256 -P /tmp/memcached.pid
-d选项是启动一个守护进程,
-m是分配给Memcache使用的内存数量,单位是MB,这里是10MB,
-u是运行Memcache的用户,这里是root,
-l是监听的服务器IP地址,如果有多个地址的话,这里指定了服务器的IP地址192.168.0.200,
-p是设置Memcache监听的端口,这里设置了12000,最好是1024以上的端口,
-c选项是最大运行的并发连接数,默认是1024,这里设置了256,按照你服务器的负载量来设定,
-P是设置保存Memcache的pid文件,这里是保存在 /tmp/memcached.pid,
2.如果要结束Memcache进程,执行:
# kill `cat /tmp/memcached.pid`
也可以启动多个守护进程,不过端口不能重复。
3.重启apache,service httpd restart

java的客户端连接程序:
将java_memcached-release_1.6.zip解压后的目录中的java_memcached-release_2.0.jar文件复制到java项目的lib目录下。

package utils.cache;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
* 使用memcached的缓存实用类.
*/
public class MemCached
{
// 创建全局的唯一实例
protected static MemCachedClient mcc = new MemCachedClient();

protected static MemCached memCached = new MemCached();

// 设置与缓存服务器的连接池
static {
// 服务器列表和其权重
String[] servers = {"127.0.0.1:11211"};
Integer[] weights = {3};
// 获取socke连接池的实例对象
SockIOPool sockIOPool = SockIOPool.getInstance();
// 设置服务器信息
sockIOPool.setServers( servers );
sockIOPool.setWeights( weights );
// 设置初始连接数、最小和最大连接数以及最大处理时间
sockIOPool.setInitConn( 5 );
sockIOPool.setMinConn( 5 );
sockIOPool.setMaxConn( 250 );
sockIOPool.setMaxIdle( 1000 * 60 * 60 * 6 );
// 设置主线程的睡眠时间
sockIOPool.setMaintSleep( 30 );
// 设置TCP的参数,连接超时等
sockIOPool.setNagle( false );
sockIOPool.setSocketTO( 3000 );
sockIOPool.setSocketConnectTO( 0 );
//sockIOPool.setFailover(bFailover);
//sockIOPool.setAliveCheck(bAliveCheck);
// 初始化连接池
sockIOPool.initialize();
// 压缩设置,超过指定大小(单位为K)的数据都会被压缩
if (memCachedClient == null)
{
mcc = new MemCachedClient(sPoolName);
mcc.setCompressEnable(true);
mcc.setCompressThreshold(4096);
mcc.setPrimitiveAsString(true);
}
}
/*
<h3>基于Spring的配置,如下:</h3>
<pre>
<bean id="memCachedService" class="com.ms.memcached.MemCachedServiceImpl">
<constructor-arg index="0" value="${memcached.pool.name}" />
<constructor-arg index="1" value="${memcached.pool.servers}" />
<constructor-arg index="2" value="${memcached.pool.initConn}" />
<constructor-arg index="3" value="${memcached.pool.maxConn}" />
<constructor-arg index="4" value="${memcached.pool.minConn}" />
<constructor-arg index="5" value="${memcached.pool.socketTO}" />
<constructor-arg index="6" value="${memcached.pool.maintSleep}" />
<constructor-arg index="7" value="${memcached.pool.nagle}" />
<constructor-arg index="8" value="${memcached.pool.failover}" />
<constructor-arg index="9" value="${memcached.pool.aliveCheck}" />
</bean>
</pre>
<h3>利用com.MS.cache.properties来设置参数,如下:</h3>
<pre>
memcached.pool.name = MS
memcached.pool.servers = 192.168.9.132:12000,192.168.9.133:12000
memcached.pool.initConn = 128
memcached.pool.maxConn = 1024
memcached.pool.minConn = 20
memcached.pool.socketTO = 3000
memcached.pool.maintSleep = 30
memcached.pool.nagle = false
memcached.pool.failover = true
memcached.pool.aliveCheck = true
</pre>
*/

/**
* 保护型构造方法,不允许实例化!
*/
protected MemCached()
{

}

/**
* 获取唯一实例.
*/
public static MemCached getInstance()
{
return memCached;
}

/**
* 添加一个指定的值到缓存中.
* @param key
* @param value
*/
//新增指定key的缓存内容,但不覆盖已存在的内容。
public boolean add(String key, Object value)
{
return mcc.add(key, value);
}

//expiry过期时间
public boolean add(String key, Object value, Date expiry)
{
return mcc.add(key, value, expiry);
}

//新增或覆盖指定Key的缓存内容
public boolean set(String key, Object value)
{
return mcc.set(key, value);
}

//lExpiry过期时间
public boolean set(String key, Object value, long lExpiry)
{
return mcc.set(key, value, new Date(lExpiry));
}

//根据指定的Key获取缓存内容
public boolean get(String key)
{
return mcc.get(key);
}

//根据指定Key更新缓存内容
public boolean replace(String key, Object value)
{
return mcc.replace(key, value);
}

//lExpiry 指定的时间
public boolean replace(String key, Object value, long lExpiry)
{
return mcc.replace(key, value, new Date(lExpiry));
}
//根据指定Key删除缓存内容
public boolean delete(String key, Object value)
{
return mcc.delete(key, value);
}

//根据指定Key在指定时间后删除缓存内容
public boolean delete(String key, Object value, long lExpiry)
{
return mcc.delete(key, value, new Date(lExpiry));
}

//检测Cache中当前Key是否存在
public boolean exists(String key)
{
return mcc.exists(key);
}
//根据指定一批Key批量获取缓存内容。
/*
* @param sKeys 指定的一批Key。
* @return Object[oValue]
*/
public Object[] getMultiArray(String[] sKeys) throws ServiceException
{
return memCachedClient.getMultiArray(sKeys);
}
/**
* 根据指定一批Key批量获取缓存内容。
*
* @param sKeys 指定的一批Key。
* @return Map<sKey, oValue>
*/
public Map<String, Object> getMulti(String[] sKeys) throws ServiceException
{
return memCachedClient.getMulti(sKeys);
}

public static void main(String[] args)
{
MemCached memCached= MemCached.getInstance();
memCached.add("hello", 234);
System.out.print("get value : " + memCached.get("hello"));
}
}

那么我们就可以通过简单的像main方法中操作的一样存入一个变量,然后再取出进行查看,我们可以看到先调用了add,然后再进行get,我们运行一次 后,234这个值已经被我们存入了memcached的缓存中的了,我们将main方法中红色的那一行注释掉后,我们再运行还是可以看到get到的 value也是234,即缓存中我们已经存在了数据了。
对基本的数据我们可以操作,对于普通的POJO而言,如果要进行存储的话,那么比如让其实现java.io.Serializable接口,因为 memcached是一个分布式的缓存服务器,多台服务器间进行数据共享需要将对象序列化的,所以必须实现该接口,否则会报错的。
Entity
/**
* 获取当前实体的缓存Id
*
* @return
*/
public String getCacheId()
{
return getCacheId(this.getClass(), sBreedId);
}

get
public Breed getBreedById(String sBreedId) throws ServiceException
{
Breed breed = (Breed)memCachedService.get(getCacheId(Breed.class, sBreedId));

if(breed == null)
{
breed = service.get("breed.getBreedById", sBreedId);

if(breed != null)
{
memCachedService.set(breed.getBreedId(), breed);
}
}

return breed;
}

save
memCachedService.set(spider.getCacheId(), breed);

update
memCachedService.replace(spider.getCacheId(), breed);

remove
memCachedService.delete(getCacheId(Spider.class, IbreedId));

memCachedService.delete(breed.getCacheId());
listAll
public List listAll() throws ServiceException
{
List breeds = new ArrayList ();

List breedIds = (List)memCachedService.get(getKeyByMap("Breed", null));

if(ObjectUtils.isEmpty(breedIds))
{
breeds = service.list("breed.getAllBreed", null);

if (!ObjectUtils.isEmpty(breeds))
{
breedIds = new ArrayList();

for (Breed breed : breeds)
{
breedIds.add(breed.getBreedId());
}

memCachedService.set(getKeyByMap("Breed", null), breedIds);
}
}
else
{
for (String sBreedId : breedIds)
{
Breed breed = getBreedById(sBreedId);

if (breed != null)
{
breeds.add(breed);
}
}
}

return breeds;
}

D. memcached跟jdk版本有关系吗

Memcached是一个开源的,C写的分布式key-value缓存,XMemcached只是它的一个访问客户端。
Memcached通过网络协议跟客户端交互,通过客户端你才可以去使用memcached,xmemcached是它的java客户端之一。

E. 谈谈redis,memcache的区别和具体应用场景

Memcached是以LiveJurnal旗下DangaInteractive公司的BardFitzpatric为首开发的高性能分布式内存缓存服务器。其本质上就是一个内存key-value数据库,但是不支持数据的持久化,服务器关闭之后数据全部丢失。Memcached使用C语言开发,在大多数像Linux、BSD和Solaris等POSIX系统上,只要安装了libevent即可使用。Memcached的客户端软件实现非常多,包括C/C++,PHP,Java,Python,Ruby,Perl,Erlang,Lua等。当前Memcached使用广泛,除了LiveJournal以外还有Wikipedia、Flickr、Twitter、Youtube和WordPress等。

F. java中memcache怎么用

1. memcached client for java客户端API:memcached client for java

引入jar包:java-memcached-2.6.2.jar

package com.pcitc.memcached;

import com.danga.MemCached.*;

public class TestMemcached {
public static void main(String[] args) {
/* 初始化SockIOPool,管理memcached的连接池 */
String[] servers = { "192.168.1.111:11211" };
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(servers);
pool.setFailover(true);
pool.setInitConn(10);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setAliveCheck(true);
pool.initialize();
/* 建立MemcachedClient实例 */
MemCachedClient memCachedClient = new MemCachedClient();
for (int i = 0; i < 10; i++) {
/* 将对象加入到memcached缓存 */
boolean success = memCachedClient.set("" + i, "Hello!");
/* 从memcached缓存中按key值取对象 */
String result = (String) memCachedClient.get("" + i);
System.out.println(String.format("set( %d ): %s", i, success));
System.out.println(String.format("get( %d ): %s", i, result));
}
}
}

2. spymemcached客户端API:spymemcached client

引入jar包:spymemcached-2.10.3.jar

package com.pcitc.memcached;

import java.net.InetSocketAddress;
import java.util.concurrent.Future;

import net.spy.memcached.MemcachedClient;

public class MClient {

public static void main(String[] args) {
setValue();
getValue();
}

// 用spymemcached将对象存入缓存
public static void setValue() {
try {
/* 建立MemcachedClient 实例,并指定memcached服务的IP地址和端口号 */
MemcachedClient mc = new MemcachedClient(new InetSocketAddress(
"192.168.1.111", 11211));
Future<Boolean> b = null;
/* 将key值,过期时间(秒)和要缓存的对象set到memcached中 */
b = mc.set("neead", 900, "someObject");
if (b.get().booleanValue() == true) {
mc.shutdown();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

// 用spymemcached从缓存中取得对象
public static void getValue() {
try {
/* 建立MemcachedClient 实例,并指定memcached服务的IP地址和端口号 */
MemcachedClient mc = new MemcachedClient(new InetSocketAddress(
"192.168.1.111", 11211));
/* 按照key值从memcached中查找缓存,不存在则返回null */
Object b = mc.get("neead");
mc.shutdown();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

3.两种API比较
memcached client for java:较早推出的memcached JAVA客户端API,应用广泛,运行比较稳定。
spymemcached:A simple, asynchronous, single-threaded memcached client written in java. 支持异步,单线程的memcached客户端,用到了java1.5版本的concurrent和nio,存取速度会高于前者,但是稳定性不好,测试中常报timeOut等相关异常。
由于memcached client for java发布了新版本,性能上有所提高,并且运行稳定,所以建议使用memcached client for java

G. 如何用java redis hbase

比如 MongoDB 和 CouchDB。每个数据存储都有其优势和劣势,特别是当应用于特定领域时。 本期的 Java 开发 2.0 关注的是 Redis,一种轻量级键值对数据存储。多数 NoSQL 实现本质上都是键值对,但是 Redis 支持非常丰富的值集,其中包括字符串、列表、集以及散列。因此,Redis 通常被称为数据结构服务器。Redis 也以异常快速而闻名,这使得它成为某一特定类型使用案例的最优选择。 当我们想要了解一种新事物时,将其同熟知的事物进行比较可能会有所帮助,因此,我们将通过对比其与 memcached 的相似性以开启 Redis 探索之旅。接着我们将介绍 Redis 的主要功能,这些功能可以使其在某些应用场景可以胜过 memcached。最后我将向您展示如何将 Redis 作为一个传统数据存储用于模型对象。Redis 和 memcached Memcached 是一个众所周知的内存对象缓存系统,通过将目标键和值导入内存缓存运行。因此,Memcached 能回避读取磁盘时发生的 I/O 成本问题。在 Web 应用程序和数据库之间粘贴 memcached 时会产生更好的读取性能。因此,对于那些需要快速数据查询的应用程序,Memcached 是一个不错的选择。其中的一个例子为股票查询服务,需要另外访问数据库获取相对静态数据,如股票名称或价格信息。 MemcacheDB 将Redis 与 memcached 相比较并不公平,它与 MemcacheDB 相比要好的多,MemcacheDB 是一个分布式键值对存储系统,专为数据持久化而设计。MemcacheDB 与 Redis 较为相似,其新增优势可以使其轻松地与 memcached 实现的客户端进行通信。 但是memcached 也有其局限性,其中一个事实就是它所有的值均是简单的字符串。Redis 作为 memcached 的替代者,支持更加丰富的功能集。一些基准 (benchmarks) 也表明 Redis 的速度要比 memcached 快很多。Redis 提供的丰富数据类型使其可以在内存中存储更为复杂的数据,这是使用 memcached 无法实现的。同 memcached 不一样,Redis 可以持久化其数据。 Redis 解决了一个重大的缓存问题,而其丰富的功能集又为其找到了其他用途。由于 Redis 能够在磁盘上存储数据以及跨节点复制数据,因而可以作为数据仓库用于传统数据模式(也就是说,您可以使用 Redis,就像使用 RDBMS 一样)。Redis 还经常被用作队列系统。在本用例中,Redis 是备份和工作队列持久化存储(利用 Redis 的列表类型)的基础。GitHub 是以此种方法使用 Redis 的大规模基础架构示例准备好 Redis,立即开始! 要开始使用 Redis,您需要访问它,可以通过本地安装或者托管供应商来实现访问。如果您使用的 MAC,安装过程可能就不那么简单。

H. memcached和ecache的区别

Ehcache是纯Java编写的,通信是通过RMI方式,适用于基于Java技术的项目。MemCached服务器端是C编写的,客户端有多个语言实现,如C,PHP(淘宝,sina等各大门户网站),Python(豆瓣网), Java(Xmemcached,spymemcached)。MemcaChed服务器端是使用文本或者二进制通信的。
分布式:MemcaChed不完全。集群默认不实现,Ehcache支持。
集群:MemcaChed可通过客户端实现。Ehcache支持(默认是异步同步)。
持久化:MemcaChed可通过第三方应用实现,如sina研发的memcachedb,将cache的数据保存到[url=]Berkerly DB[/url]。Ehcache支持。持久化到本地硬盘,生成一个.data和.index文件。cache初始化时会自动查找这两个文件,将数据放入cache。
效率:MemcaChed高。Ehcache高于Memcache。
容灾:MemcaChed可通过客户端实现。Ehcache支持。
缓存数据方式:MemcaChed缓存在MemCached server向系统申请的内存中。Ehcache可以缓存在内存(JVM中),也可以缓存在硬盘。通过CacheManager管理cache。多个CacheManager可配置在一个JVM内,CacheManager可管理多个cache。
缓存过期移除策略:MemcaChed是LRU。Ehcache是LRU(默认),FIFO,LFU。
缺点:MemcaChed功能不完善,相对于Ehcache效率低。Ehcache只适用于java体系,只能用java编写客户端。
优点:MemcaChed简洁,灵活,所有支持socket的语言都能编写其客户端。Ehcache效率高。功能强大。

I. 你使用过 Memcache 缓存吗如果使用过,能够简单的描述一下它的工作原理吗

首先 memcached 是以守护程序方式运行于一个或多个服务器中,随时接受客户端的连接操作,客户端可以由各种语言编写,目前已知的客户端 API 包括 Perl/PHP/Python/Ruby/Java/C#/C 等等。PHP 等客户端在与 memcached 服务建立连接之后,接下来的事情就是存取对象了,每个被存取的对象都有一个唯一的标识符 key,存取操作均通过这个 key 进行,保存到 memcached 中的对象实际上是放置内存中的,并不是保存在 cache 文件中的,这也是为什么PHP内存缓存技术memcached 能够如此高效快速的原因。注意,这些对象并不是持久的,服务停止之后,里边的数据就会丢失。

阅读全文

与javamemcached客户端相关的资料

热点内容
单片机代码跳掉 浏览:447
程序员谈薪水压价 浏览:861
荣耀10青春版支持方舟编译啊 浏览:158
最优估计pdf 浏览:826
androiddrawtext字体 浏览:669
c语言源编辑源程序编译 浏览:821
手里捏东西真的可以解压吗 浏览:265
编译原理画状态表 浏览:28
用echo命令产生下列输出 浏览:360
在内网如何访问服务器 浏览:961
java导入oracle数据库 浏览:134
坚朗内开内倒铝条算法 浏览:259
华为阅读新建文件夹 浏览:770
幻塔如何选择服务器 浏览:221
解压先把文件压到系统盘 浏览:822
access压缩和修复数据库 浏览:791
光纤交换机命令 浏览:513
白色桌放什么文件夹 浏览:296
分治算法思想 浏览:151
s曲线加减速算法 浏览:403