package com.ilivoo.memcached;

import java.net.InetSocketAddress;

import com.thimbleware.jmemcached.CacheImpl;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import com.thimbleware.jmemcached.MemCacheDaemon;
import com.thimbleware.jmemcached.storage.CacheStorage;
import com.thimbleware.jmemcached.storage.bytebuffer.BlockStorageCacheStorage;
import com.thimbleware.jmemcached.storage.bytebuffer.BlockStoreFactory;
import com.thimbleware.jmemcached.storage.bytebuffer.ByteBufferBlockStore;
import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap;
import com.thimbleware.jmemcached.storage.mmap.MemoryMappedBlockStore;

public class MemcachedManager {
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws Exception {
		boolean blockStore = false;
		boolean memoryMapped = false;
		final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();

		CacheStorage<Key, LocalCacheElement> storage;
		if (blockStore) {
			BlockStoreFactory blockStoreFactory = ByteBufferBlockStore.getFactory();

			storage = new BlockStorageCacheStorage(8, (int) 1024000, 8, 10240000, 1000, blockStoreFactory);
		} else if (memoryMapped) {
			BlockStoreFactory blockStoreFactory = MemoryMappedBlockStore.getFactory();

			storage = new BlockStorageCacheStorage(8, (int) 1024000, 8, 1024000, 1000, blockStoreFactory);
		} else {
			storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, 1000, 10240000);
		}

		daemon.setCache(new CacheImpl(storage));
		daemon.setBinary(true);
		daemon.setAddr(new InetSocketAddress(12121));
		daemon.setIdleTime(0);
		daemon.setVerbose(false);
		daemon.start();

		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			public void run() {
				if (daemon.isRunning())
					daemon.stop();
			}
		}));
	}
}
