`

基于Xmemcached实现并发安全写

 
阅读更多

POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.save.mc</groupId>
	<artifactId>save-mc-api</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>api</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.googlecode.xmemcached</groupId>
			<artifactId>xmemcached</artifactId>
			<version>2.0.0</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

 Class:

package com.save.mc.api;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class XMemcachedManager {

	public static MemcachedClient getInstance() {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses("173.1.3.102:11211"));
		try {
			return builder.build();
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("memcached connection failed");
	}

	public static void main(String[] args) throws TimeoutException,
			InterruptedException, MemcachedException {
		for (int i = 0; i < 100; i++) {
			final int b = i;
			new Thread() {
				public void run() {
					int a;
					try {
						a = SaveMemcachedClient.INSTANCE
								.saveset("save_ttt9", b);
						System.out.println(a);
					} catch (TimeoutException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (MemcachedException e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
	}

}

 

package com.save.mc.api;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.CASOperation;
import net.rubyeye.xmemcached.Counter;
import net.rubyeye.xmemcached.GetsResponse;
import net.rubyeye.xmemcached.KeyIterator;
import net.rubyeye.xmemcached.KeyProvider;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientCallable;
import net.rubyeye.xmemcached.MemcachedClientStateListener;
import net.rubyeye.xmemcached.auth.AuthInfo;
import net.rubyeye.xmemcached.buffer.BufferAllocator;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.impl.ReconnectRequest;
import net.rubyeye.xmemcached.networking.Connector;
import net.rubyeye.xmemcached.transcoders.Transcoder;
import net.rubyeye.xmemcached.utils.Protocol;

import com.save.mc.api.bugfix.AbsCASOpt;
import com.save.mc.api.bugfix.XCASOperation;
import com.save.mc.api.operation.SaveAccumulateCASOperation;
import com.save.mc.api.operation.SaveCASOperation;

@SuppressWarnings("deprecation")
public enum SaveMemcachedClient implements MemcachedClient{
	
	INSTANCE;
	
	private MemcachedClient client = XMemcachedManager.getInstance(); 
   
	public void setClient(MemcachedClient c){
		this.client = c;
	}
	
	public MemcachedClient getClient(){
		return this.client;
	}

/**
	 * 此方法描述的是:安全写,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param value
	 *            - 值
	 */
	public <T> T saveset(String key,T value) throws TimeoutException, InterruptedException, MemcachedException {
		return this.savecas(key, new SaveCASOperation<T>(value));
	}
	
	/**
	 * 此方法描述的是:安全写,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 * @param value
	 *            - 值
	 */
	public <T> T saveset(String key,int exp, T value) throws TimeoutException, InterruptedException, MemcachedException {
		return this.savecas(key, new SaveCASOperation<T>(exp,value));
	}
	
	/**
	 * 此方法描述的是:安全累加,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param value
	 *            - 增加的步长值,支持Integer,Long,Double,Float,BigDecimal
	 */
	public <T> T saveAcc(String key,T value) throws TimeoutException, InterruptedException, MemcachedException {
		return this.savecas(key, new SaveAccumulateCASOperation<T>(value));
	}
	
	/**
	 * 此方法描述的是:安全累加,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 * @param value
	 *            - 增加的步长值,支持Integer,Long,Double,Float,BigDecimal
	 */
	public <T> T saveAcc(String key,int exp, T value) throws TimeoutException, InterruptedException, MemcachedException {
		return this.savecas(key, new SaveAccumulateCASOperation<T>(exp,value));
	}
	
	/**
	 * 此方法描述的是:安全递增++,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 */
	public Integer saveIntegerInc(String key) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, 1);
	}
	
	/**
	 * 此方法描述的是:安全递增++,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 * @param value
	 *            - 值
	 */
	public Integer saveIntegerInc(String key,int exp) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, exp, 1);
	}
	
	/**
	 * 此方法描述的是:安全递增++,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 */
	public Long saveLongInc(String key) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, 1L);
	}
	
	/**
	 * 此方法描述的是:安全递增++,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 * @param value
	 *            - 值
	 */
	public Long saveLongInc(String key,int exp) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, exp, 1L);
	}
	
	/**
	 * 此方法描述的是:安全递增++,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 */
	public Double saveDoubleInc(String key) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, 1.0);
	}
	
	/**
	 * 此方法描述的是:安全递增++,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 */
	public Double saveDoubleInc(String key,int exp) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, exp, 1.0);
	}
	
	/**
	 * 此方法描述的是:安全递增++,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 */
	public Float saveFloatInc(String key) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, 1.0F);
	}
	
	/**
	 * 此方法描述的是:安全递增++,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 */
	public Float saveFloatInc(String key,int exp) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, exp, 1.0F);
	}
	
	/**
	 * 此方法描述的是:安全递增++,永久存储
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 */
	public BigDecimal saveBigDecimalInc(String key) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, new BigDecimal(1));
	}
	
	/**
	 * 此方法描述的是:安全递增++,指定存储有效期
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午1:49:47
	 * @param key
	 *            - 关键字
	 * @param exp
	 *            - 存储有效时间(秒) 0-永久存储
	 */
	public BigDecimal saveBigDecimalInc(String key,int exp) throws TimeoutException, InterruptedException, MemcachedException {
		return this.saveAcc(key, exp, new BigDecimal(1));
	}
	
	/**
	 * 此方法描述的是:安全写
	 * 
	 * @author: zhangyang33@sinopharm.com
	 * @version: 2015年1月7日 下午2:45:20
	 * @param key
	 *            - 关键字
	 * @param casOpt
	 *            - 自定义适配器
	 */
	public <T> T savecas(String key,final AbsCASOpt<T> casOpt) throws TimeoutException, InterruptedException, MemcachedException {
        GetsResponse<T> response = client.gets(key);
        T t = casOpt.initValue();
        final int exp = casOpt.initExp();
        final int max = AbsCASOpt.MAX_TRIES;
        if (response == null){
            for (int i = 0; i < max; i++) {
                if (client.add(key, exp, t)){
                    return t;
                }else{
                    try {
                        return savecas(key, casOpt);
                    } catch (Exception e) {
                    	e.printStackTrace();
                    }
                }
            }
        }else{
        	XCASOperation<T> operation = new XCASOperation<T>() {  
                private T lastValue;  
                public int getMaxTries() {  
                    return AbsCASOpt.MAX_TRIES;  
                }  

                public T getNewValue(long currentCAS, T currentValue) {  
                    lastValue = casOpt.getNewValue(currentValue);  
                    return lastValue;  
                }  

                public T getLastValue(){  
                    return this.lastValue;  
                }  
            };  
             boolean casFlag = client.cas(key, exp, operation);
            if (casFlag){
                return operation.getLastValue();
            }
        }
		return t;
    }
public void setMergeFactor(int mergeFactor) { client.setMergeFactor(mergeFactor); } public long getConnectTimeout() { return client.getConnectTimeout(); } public void setConnectTimeout(long connectTimeout) { client.setConnectTimeout(connectTimeout); } public Connector getConnector() { return client.getConnector(); } public void setOptimizeGet(boolean optimizeGet) { client.setOptimizeGet(optimizeGet); } public void setOptimizeMergeBuffer(boolean optimizeMergeBuffer) { client.setOptimizeMergeBuffer(optimizeMergeBuffer); } public boolean isShutdown() { return client.isShutdown(); } public void addServer(String server, int port) throws IOException { client.addServer(server,port); } public void addServer(InetSocketAddress inetSocketAddress) throws IOException { client.addServer(inetSocketAddress); } public void addServer(String hostList) throws IOException { client.addServer(hostList); } public List<String> getServersDescription() { return client.getServersDescription(); } public void removeServer(String hostList) { client.removeServer(hostList); } @Deprecated public void setBufferAllocator(BufferAllocator bufferAllocator) { client.setBufferAllocator(bufferAllocator); } public <T> T get(String key, long timeout, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.get(key, timeout, transcoder); } public <T> T get(String key, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.get(key, timeout); } public <T> T get(String key, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.get(key, transcoder); } public <T> T get(String key) throws TimeoutException, InterruptedException, MemcachedException { return client.get(key); } public <T> GetsResponse<T> gets(String key, long timeout, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(key, timeout, transcoder); } public <T> GetsResponse<T> gets(String key) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(key); } public <T> GetsResponse<T> gets(String key, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(key, timeout); } @SuppressWarnings("rawtypes") public <T> GetsResponse<T> gets(String key, Transcoder transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(key, transcoder); } public <T> Map<String, T> get(Collection<String> keyCollections, long opTimeout, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.get(keyCollections,opTimeout,transcoder); } public <T> Map<String, T> get(Collection<String> keyCollections, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.get(keyCollections, transcoder); } public <T> Map<String, T> get(Collection<String> keyCollections) throws TimeoutException, InterruptedException, MemcachedException { return client.get(keyCollections); } public <T> Map<String, T> get(Collection<String> keyCollections, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.get(keyCollections, timeout); } public <T> Map<String, GetsResponse<T>> gets( Collection<String> keyCollections, long opTime, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(keyCollections, opTime, transcoder); } public <T> Map<String, GetsResponse<T>> gets( Collection<String> keyCollections) throws TimeoutException, InterruptedException, MemcachedException { return client.gets(keyCollections); } public <T> Map<String, GetsResponse<T>> gets( Collection<String> keyCollections, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.gets( keyCollections, timeout); } public <T> Map<String, GetsResponse<T>> gets( Collection<String> keyCollections, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.gets( keyCollections, transcoder); } public <T> boolean set(String key, int exp, T value, Transcoder<T> transcoder, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.set(key, exp, value, transcoder, timeout); } public boolean set(String key, int exp, Object value) throws TimeoutException, InterruptedException, MemcachedException { return client.set(key, exp, value); } public boolean set(String key, int exp, Object value, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.set(key, exp, value, timeout); } public <T> boolean set(String key, int exp, T value, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.set(key, exp, value, transcoder); } public void setWithNoReply(String key, int exp, Object value) throws InterruptedException, MemcachedException { client.setWithNoReply(key, exp, value); } public <T> void setWithNoReply(String key, int exp, T value, Transcoder<T> transcoder) throws InterruptedException, MemcachedException { client.setWithNoReply(key, exp, value, transcoder); } public <T> boolean add(String key, int exp, T value, Transcoder<T> transcoder, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.add(key, exp, value, transcoder, timeout); } public boolean add(String key, int exp, Object value) throws TimeoutException, InterruptedException, MemcachedException { return client.add(key, exp, value); } public boolean add(String key, int exp, Object value, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.add(key, exp, value, timeout); } public <T> boolean add(String key, int exp, T value, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.add(key, exp, value, transcoder); } public void addWithNoReply(String key, int exp, Object value) throws InterruptedException, MemcachedException { client.addWithNoReply(key, exp, value); } public <T> void addWithNoReply(String key, int exp, T value, Transcoder<T> transcoder) throws InterruptedException, MemcachedException { client.addWithNoReply(key, exp, value, transcoder); } public <T> boolean replace(String key, int exp, T value, Transcoder<T> transcoder, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.replace(key, exp, value, transcoder, timeout); } public boolean replace(String key, int exp, Object value) throws TimeoutException, InterruptedException, MemcachedException { return client.replace(key, exp, value); } public boolean replace(String key, int exp, Object value, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.replace(key, exp, value, timeout); } public <T> boolean replace(String key, int exp, T value, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.replace(key, exp, value, transcoder); } public void replaceWithNoReply(String key, int exp, Object value) throws InterruptedException, MemcachedException { client.replaceWithNoReply(key, exp, value); } public <T> void replaceWithNoReply(String key, int exp, T value, Transcoder<T> transcoder) throws InterruptedException, MemcachedException { client.replaceWithNoReply(key, exp, value, transcoder); } public boolean append(String key, Object value) throws TimeoutException, InterruptedException, MemcachedException { return client.append(key, value); } public boolean append(String key, Object value, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.append(key, value, timeout); } public void appendWithNoReply(String key, Object value) throws InterruptedException, MemcachedException { client.appendWithNoReply(key, value); } public boolean prepend(String key, Object value) throws TimeoutException, InterruptedException, MemcachedException { return client.prepend(key, value); } public boolean prepend(String key, Object value, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.prepend(key, value, timeout); } public void prependWithNoReply(String key, Object value) throws InterruptedException, MemcachedException { client.prependWithNoReply(key, value); } public boolean cas(String key, int exp, Object value, long cas) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, value, cas); } public <T> boolean cas(String key, int exp, T value, Transcoder<T> transcoder, long timeout, long cas) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, value, transcoder, timeout, cas); } public boolean cas(String key, int exp, Object value, long timeout, long cas) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, value, timeout, cas); } public <T> boolean cas(String key, int exp, T value, Transcoder<T> transcoder, long cas) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, value, transcoder, cas); } public <T> boolean cas(String key, int exp, CASOperation<T> operation, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, operation, transcoder); } public <T> boolean cas(String key, int exp, GetsResponse<T> getsReponse, CASOperation<T> operation, Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException { return client.cas( key, exp, getsReponse, operation, transcoder); } public <T> boolean cas(String key, int exp, GetsResponse<T> getsReponse, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { return client.cas(key, exp, getsReponse, operation); } public <T> boolean cas(String key, GetsResponse<T> getsResponse, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { return client.cas(key, getsResponse, operation); } public <T> boolean cas(String key, int exp, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { return client.cas(key,exp,operation); } public <T> boolean cas(String key, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { return client.cas(key, operation); } public <T> void casWithNoReply(String key, GetsResponse<T> getsResponse, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { client.casWithNoReply(key, getsResponse, operation); } public <T> void casWithNoReply(String key, int exp, GetsResponse<T> getsReponse, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { client.casWithNoReply(key, exp, getsReponse, operation); } public <T> void casWithNoReply(String key, int exp, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { client.casWithNoReply(key, exp, operation); } public <T> void casWithNoReply(String key, CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException { client.casWithNoReply(key, operation); } @Deprecated public boolean delete(String key, int time) throws TimeoutException, InterruptedException, MemcachedException { return client.delete(key, time); } public boolean delete(String key, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException { return client.delete(key, opTimeout); } public boolean delete(String key, long cas, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException { return client.delete(key); } public boolean touch(String key, int exp, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException { return client.touch(key, exp, opTimeout); } public boolean touch(String key, int exp) throws TimeoutException, InterruptedException, MemcachedException { return client.touch(key, exp); } public <T> T getAndTouch(String key, int newExp, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException { return client.getAndTouch(key, newExp, opTimeout); } public <T> T getAndTouch(String key, int newExp) throws TimeoutException, InterruptedException, MemcachedException { return client.getAndTouch(key, newExp); } public Map<InetSocketAddress, String> getVersions() throws TimeoutException, InterruptedException, MemcachedException { return client.getVersions(); } public long incr(String key, long delta) throws TimeoutException, InterruptedException, MemcachedException { return client.incr(key, delta); } public long incr(String key, long delta, long initValue) throws TimeoutException, InterruptedException, MemcachedException { return client.incr(key, delta, initValue); } public long incr(String key, long delta, long initValue, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.incr(key, delta, initValue, timeout); } public long decr(String key, long delta) throws TimeoutException, InterruptedException, MemcachedException { return client.decr(key, delta); } public long decr(String key, long delta, long initValue) throws TimeoutException, InterruptedException, MemcachedException { return client.decr(key, delta, initValue); } public long decr(String key, long delta, long initValue, long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.decr(key, delta, initValue, timeout); } public void flushAll() throws TimeoutException, InterruptedException, MemcachedException { client.flushAll(); } public void flushAllWithNoReply() throws InterruptedException, MemcachedException { client.flushAllWithNoReply(); } public void flushAll(long timeout) throws TimeoutException, InterruptedException, MemcachedException { client.flushAll(timeout); } public void flushAll(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException { client.flushAll(address); } public void flushAllWithNoReply(InetSocketAddress address) throws MemcachedException, InterruptedException { client.flushAllWithNoReply(address); } public void flushAll(InetSocketAddress address, long timeout) throws MemcachedException, InterruptedException, TimeoutException { client.flushAll(address, timeout); } @Deprecated public void flushAll(String host) throws TimeoutException, InterruptedException, MemcachedException { client.flushAll(host); } public Map<String, String> stats(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException { return client.stats(address); } public Map<String, String> stats(InetSocketAddress address, long timeout) throws MemcachedException, InterruptedException, TimeoutException { return client.stats(address, timeout); } public Map<InetSocketAddress, Map<String, String>> getStats(long timeout) throws MemcachedException, InterruptedException, TimeoutException { return client.getStats(timeout); } public Map<InetSocketAddress, Map<String, String>> getStats() throws MemcachedException, InterruptedException, TimeoutException { return client.getStats(); } public Map<InetSocketAddress, Map<String, String>> getStatsByItem( String itemName) throws MemcachedException, InterruptedException, TimeoutException { return client.getStatsByItem(itemName); } public void shutdown() throws IOException { client.shutdown(); } public boolean delete(String key) throws TimeoutException, InterruptedException, MemcachedException { return client.delete(key); } @SuppressWarnings("rawtypes") public Transcoder getTranscoder() { return client.getTranscoder(); } @SuppressWarnings("rawtypes") public void setTranscoder(Transcoder transcoder) { client.setTranscoder(transcoder); } public Map<InetSocketAddress, Map<String, String>> getStatsByItem( String itemName, long timeout) throws MemcachedException, InterruptedException, TimeoutException { return client.getStatsByItem(itemName, timeout); } public long getOpTimeout() { return client.getOpTimeout(); } public void setOpTimeout(long opTimeout) { client.setOpTimeout(opTimeout); } public Map<InetSocketAddress, String> getVersions(long timeout) throws TimeoutException, InterruptedException, MemcachedException { return client.getVersions(timeout); } @Deprecated public Collection<InetSocketAddress> getAvaliableServers() { return client.getAvaliableServers(); } public Collection<InetSocketAddress> getAvailableServers() { return client.getAvailableServers(); } public void addServer(String server, int port, int weight) throws IOException { client.addServer( server, port, weight); } public void addServer(InetSocketAddress inetSocketAddress, int weight) throws IOException { client.addServer(inetSocketAddress, weight); } @Deprecated public void deleteWithNoReply(String key, int time) throws InterruptedException, MemcachedException { client.deleteWithNoReply(key, time); } public void deleteWithNoReply(String key) throws InterruptedException, MemcachedException { client.deleteWithNoReply(key); } public void incrWithNoReply(String key, long delta) throws InterruptedException, MemcachedException { client.incrWithNoReply(key, delta); } public void decrWithNoReply(String key, long delta) throws InterruptedException, MemcachedException { client.decrWithNoReply(key, delta); } public void setLoggingLevelVerbosity(InetSocketAddress address, int level) throws TimeoutException, InterruptedException, MemcachedException { client.setLoggingLevelVerbosity(address, level); } public void setLoggingLevelVerbosityWithNoReply(InetSocketAddress address, int level) throws InterruptedException, MemcachedException { client.setLoggingLevelVerbosityWithNoReply(address, level); } public void addStateListener(MemcachedClientStateListener listener) { client.addStateListener(listener); } public void removeStateListener(MemcachedClientStateListener listener) { client.removeStateListener(listener); } public Collection<MemcachedClientStateListener> getStateListeners() { return client.getStateListeners(); } public void flushAllWithNoReply(int exptime) throws InterruptedException, MemcachedException { client.flushAllWithNoReply(exptime); } public void flushAll(int exptime, long timeout) throws TimeoutException, InterruptedException, MemcachedException { client.flushAll(exptime, timeout); } public void flushAllWithNoReply(InetSocketAddress address, int exptime) throws MemcachedException, InterruptedException { client.flushAllWithNoReply(address, exptime); } public void flushAll(InetSocketAddress address, long timeout, int exptime) throws MemcachedException, InterruptedException, TimeoutException { client.flushAll(address, timeout, exptime); } public void setHealSessionInterval(long healConnectionInterval) { client.setHealSessionInterval(healConnectionInterval); } public void setEnableHealSession(boolean enableHealSession) { client.setEnableHealSession(enableHealSession); } public long getHealSessionInterval() { return client.getHealSessionInterval(); } public Protocol getProtocol() { return client.getProtocol(); } public void setPrimitiveAsString(boolean primitiveAsString) { client.setPrimitiveAsString(primitiveAsString); } public void setConnectionPoolSize(int poolSize) { client.setConnectionPoolSize(poolSize); } public void setEnableHeartBeat(boolean enableHeartBeat) { client.setEnableHeartBeat(enableHeartBeat); } public void setSanitizeKeys(boolean sanitizeKey) { client.setSanitizeKeys(sanitizeKey); } public boolean isSanitizeKeys() { return client.isSanitizeKeys(); } public Counter getCounter(String key) { return client.getCounter(key); } public Counter getCounter(String key, long initialValue) { return client.getCounter(key, initialValue); } @Deprecated public KeyIterator getKeyIterator(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException { return client.getKeyIterator(address); } public void setAuthInfoMap(Map<InetSocketAddress, AuthInfo> map) { client.setAuthInfoMap(map); } public Map<InetSocketAddress, AuthInfo> getAuthInfoMap() { return client.getAuthInfoMap(); } public long decr(String key, long delta, long initValue, long timeout, int exp) throws TimeoutException, InterruptedException, MemcachedException { return client.decr(key, delta, initValue, timeout, exp); } public long incr(String key, long delta, long initValue, long timeout, int exp) throws TimeoutException, InterruptedException, MemcachedException { return client.incr(key, delta, initValue, timeout, exp); } public String getName() { return client.getName(); } public void setName(String name) { client.setName(name); } public Queue<ReconnectRequest> getReconnectRequestQueue() { return client.getReconnectRequestQueue(); } public void setFailureMode(boolean failureMode) { client.setFailureMode(failureMode); } public boolean isFailureMode() { return client.isFailureMode(); } public void setKeyProvider(KeyProvider keyProvider) { client.setKeyProvider(keyProvider); } public int getTimeoutExceptionThreshold() { return client.getTimeoutExceptionThreshold(); } public void setTimeoutExceptionThreshold(int timeoutExceptionThreshold) { client.setTimeoutExceptionThreshold(timeoutExceptionThreshold); } public void invalidateNamespace(String ns) throws MemcachedException, InterruptedException, TimeoutException { client.invalidateNamespace(ns); } public void invalidateNamespace(String ns, long opTimeout) throws MemcachedException, InterruptedException, TimeoutException { client.invalidateNamespace(ns, opTimeout); } public void endWithNamespace() { client.endWithNamespace(); } public void beginWithNamespace(String ns) { client.beginWithNamespace(ns); } public <T> T withNamespace(String ns, MemcachedClientCallable<T> callable) throws MemcachedException, InterruptedException, TimeoutException { return client.withNamespace(ns, callable); } }

 

package com.save.mc.api.operation;

import com.save.mc.api.bugfix.AbsCASOpt;

public class SaveCASOperation<T> extends AbsCASOpt<T> {
	
	private int exp = 0;
	private T value;

	public SaveCASOperation(T value) {
		super();
		this.value = value;
	}

	public SaveCASOperation(int exp, T value) {
		super();
		this.exp = exp;
		this.value = value;
	}
	
	public int initExp() {
		return this.exp;
	}

	@Override
	public T initValue() {
		return this.value;
	}

	@Override
	public T getNewValue(T current) {
		return this.value;
	}



}

 

package com.save.mc.api.operation;

import java.math.BigDecimal;


public class SaveAccumulateCASOperation<T> extends SaveCASOperation<T> {

	public SaveAccumulateCASOperation(T value) {
		super(value);
	}
	
	public SaveAccumulateCASOperation(int exp, T value) {
		super(exp, value);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getNewValue(T current) {
		Object t = null;
		if (current instanceof Integer){
			t = (Integer)current + (Integer)this.initValue();
		}
		
		else if (current instanceof Long){
			t = (Long)current + (Long)this.initValue();
		}
		
		else if (current instanceof Double){
			t = (Double)current + (Double)this.initValue();
		}
		
		else if (current instanceof Float){
			t = (Float)current + (Float)this.initValue();
		}
		
		else if (current instanceof BigDecimal){
			t = ((BigDecimal)current).add((BigDecimal)this.initValue());
		}
		
		return (T) t;
	}
	
}

 

package com.save.mc.api.bugfix;

/**
 * 缓存原子性操作接口.
 *
 * @author yangz
 * @date 2013-9-3 上午9:55
 */
public abstract class AbsCASOpt<T> {

    public static final int MAX_TRIES = 8192;

    /**
     * 初始值.
     *
     * @return
     */
    public abstract T initValue();

    /**
     * 初始值过期时间, 0为永不过期.
     *
     * @return
     */
    public abstract int initExp();

    /**
     * 获取新值.
     *
     * @param current
     * @return
     */
    public abstract T getNewValue(T current);
}

 

package com.save.mc.api.bugfix;
import net.rubyeye.xmemcached.CASOperation;

/**
 * xmemcache 原子性操作.
 * @author yangz
 * @date 2013-9-3 下午4:50
 */
public interface XCASOperation<T> extends CASOperation<T>{
    /**
     * 操作成功后的值.
     * @return
     */
    public T getLastValue();
}

 

package com.save.mc.api.bugfix;

public class UnCaughtException extends Exception {

	
		/**
		 * serialVersionUID:TODO(用一句话描述这个变量表示什么)
		 *
		 * @since Ver 1.1
		 */
		
	private static final long serialVersionUID = 1L;
	
	
	
	public UnCaughtException(String e) {
		super(e);
	}



	public UnCaughtException(Exception e) {
		super(e);
	}

}

 需要说明的是,提供SaveMemcachedClient.setClient(client)方法的目的是为了方便项目通过配置页面变更Memcached地址而提供的方法:使用如下:

SaveMemcachedClient.INSTANCE.setClient(XMemcachedManager.getInstance());

 XMemcachedManager.getInstance()方法需要自己实现,动态读配置。

分享到:
评论

相关推荐

    xmemcached

    3. **线程安全**:Xmemcached保证了在多线程环境下的安全性,无需担心并发问题。 4. **自动故障转移**:当连接到的Memcached服务器出现故障时,Xmemcached能够自动检测并切换到其他正常服务器,保证服务的连续性。 ...

    xmemcached 中文开发手册

    - 基于Java NIO(非阻塞I/O),相较于传统的阻塞I/O模型,Java NIO能够更好地处理高并发场景下的连接管理,降低线程上下文切换的开销。 - 在特定情况下(如存储较小的数据时),XMemcached的表现优于Spymemcached...

    Xmemcached官方中文手册

    - **高性能**:基于NIO实现,减少网络I/O等待时间,提高处理能力。 - **简单API**:提供直观的键值对操作接口,易于理解和使用。 - **多线程支持**:允许多个线程并行操作,提升并发性能。 - **异步操作**:支持非...

    xmemcached 2.4.6.rar

    1. **高性能**:xmemcached采用了非阻塞I/O模型,能够充分利用多核处理器的性能,提供高并发下的低延迟访问。 2. **易用性**:提供简单直观的API,使得开发者可以快速上手,实现Memcached的增删查改操作。 3. **健壮...

    xmemcached-1.4.3.jar

    它采用了非阻塞I/O模型,基于NIO(New IO)框架,这使得xmemcached在处理大量并发请求时表现出色。通过非阻塞I/O,服务器可以在等待数据返回时执行其他任务,显著提高了系统资源利用率和整体性能。 其次,...

    xmemcached-1.2.4源码

    xmemcached-1.2.4的官方源码。 xmemcached XMemcached is a high performance, easy to use blocking multithreaded memcached client in java. It's nio based (using my opensource nio framework :yanf4j), ...

    Xmemcached测试实例

    XMemcached是基于 java nio的Memcached客户端,java nio相比于传统阻塞 io 模型来说,有 效率高(特别在高并发下)和资源耗费相对较少的优点。传统阻塞 IO为了提高效率,需要 创建一定数量的连接形成连接池,而 nio...

    xmemcached api doc

    xmemcached 是一个高性能、线程安全的 Java 客户端库,用于连接和操作 Memcached 分布式内存缓存系统。它提供了丰富的 API,使得开发人员能够轻松地在应用程序中集成 Memcached 功能,以提升数据访问速度和系统性能...

    Xmemcached用户指南

    - **基于Java NIO**:XMemcached采用了Java NIO技术,相比传统的阻塞I/O模型具有更高的效率,尤其是在高并发场景下。传统阻塞I/O通常需要通过创建多个连接来形成连接池以提高性能,而Java NIO仅需维持少量连接即可...

    xmemcached jar包,源文件,api

    - `xmemcached-1.3.3-sources.jar`包含了xmemcached的源代码,可以帮助开发者了解其内部实现机制,如连接管理、命令编码与解码、并发控制等,便于定制化开发和优化性能。 - `xmemcached-1.3.3-javadoc.jar`提供了...

    xmemcached1.3.5源码-附带自己写的RMI调用它的JMX服务

    xmemcached1.3.5源码-附带自己写的RMI调用它的JMX服务,使用RMI调用JMX服务的详细过程,完整的eclipse工程,直接导入即可用。还用一些运行截图,很有用。 自己写的例子,类名是BaseExample 和RMITest.

    Xmemcached一个java实现的分布式缓存

    Xmemcached是一个高性能、线程安全的Java实现的分布式缓存系统,专为Memcached设计。这个库的主要目标是提供简单、快速、无阻塞的客户端API,以便于开发人员在Java应用程序中集成和利用Memcached的强大功能。下面将...

    xmemcached-1.2.6.2

    xmemcached-1.2.6.2

    Xmemcached 缓存开源项目源码及API

    基于java nio实现的高性能可扩展的memcached客户端。虽然Java的memcached库已经很多,但是这些Java开源memcached库并没有一个是基于NIO框架编写,因此并不能够充分发挥Java NIO的性能优势.... xmemcached的项目主页...

    memcache.spymemcached,和xmemcached 三种缓存实例

    本文将深入探讨memcache的三种常见Java客户端实现:spymemcached、xmemcached和原生的memcache接口。 1. **spymemcached**: spymemcached是由Spy公司开发的一个开源Java客户端,它是Memcached最常用的Java库之一...

    xmemcached.chm文档

    xmemcached.chm帮助文档

    xmemcached 2.4.5 2.3.2

    2. 安全性改进:随着网络安全的重要性日益凸显,2.4.5版本可能加强了安全措施,例如改进了认证机制,提升了数据传输的安全性。 3. 连接池管理优化:在连接池管理方面,2.4.5可能会有更精细的配置选项和智能的连接...

    spring-xmemcached

    spring+xmemcached aop切面 需要xmemcached-1.2.5+spring-2.5.6 class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean" destroy-method="shutdown"&gt; ${XMemcached_servers} &lt;!-- ...

    xmemcached-1.4.2

    xmemcached-1.4.2最新版,可用。memcached java客户端

Global site tag (gtag.js) - Google Analytics