<commit_before>package info.noconfuse.modules.cache;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.util.Assert;

import java.util.concurrent.TimeoutException;

/**
 * An implementation of {@link org.springframework.cache.Cache} which is based on Memcached.
 * <br/>
 * Use killme2008/xmemcached as client of Memcached.
 *
 * @author <NAME>
 */
public class MemcachedCache implements Cache {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemcachedCache.class);

    private String name;

    private MemcachedClient memcachedClient;

    public MemcachedCache(String name, MemcachedClient memcachedClient) {
        Assert.notNull(name, "Cache name must be assigned");
        Assert.notNull(memcachedClient, "MemcachedClient must be assigned");
        this.name = name;
        this.memcachedClient = memcachedClient;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Object getNativeCache() {
        return memcachedClient;
    }

    @Override
    public ValueWrapper get(Object key) {
        Object data = lookup(genKey(key));
        return data == null ? null : new SimpleValueWrapper(data);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        return (T) lookup(genKey(key));
    }

    @Override
    public void put(Object key, Object value) {
        // evict if put a null value
        if (value == null) {
            evict(key);
            return;
        }

        save(genKey(key), value);
    }

    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
        ValueWrapper old = get(key);
        if (old == null)
            put(key, value);
        return old;
    }

    @Override
    public void evict(Object key) {
        delete(genKey(key));
    }

    @Override
    public void clear() {
        deleteAll();
    }

    /**
     * 通过 xmemcached 客户端访问 memcached 服务并查询缓存的数据
     *
     * @param key memcached 中的 key
     * @return memcached 中对应 key 的 value 数据
     */
    protected Object lookup(String key) {
        Object data = null;
        try {
            data = memcachedClient.get(key);
        } catch (TimeoutException e) {
            LOGGER.error("Timeout when looking up cached data for key:{}", key, e);
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted when looking up cached data for key:{}", key, e);
        } catch (MemcachedException e) {
            LOGGER.error("Failed when looking up cached data for key:{}", key, e);
        }
        return data;
    }

    /**
     * 通过 xmemcached 客户端访问 memcached 服务并保存数据<commit_msg>Reconsider exceptions handling in MemcachedCache implement<commit_after>package info.noconfuse.modules.cache;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.util.Assert;

import java.util.concurrent.TimeoutException;

/**
 * An implementation of {@link org.springframework.cache.Cache} which is based on Memcached.
 * <br/>
 * Use killme2008/xmemcached as client of Memcached.
 *
 * @author <NAME>
 */
public class MemcachedCache implements Cache {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemcachedCache.class);

    private String name;

    private MemcachedClient memcachedClient;

    public MemcachedCache(String name, MemcachedClient memcachedClient) {
        Assert.notNull(name, "Cache name must be assigned");
        Assert.notNull(memcachedClient, "MemcachedClient must be assigned");
        this.name = name;
        this.memcachedClient = memcachedClient;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Object getNativeCache() {
        return memcachedClient;
    }

    @Override
    public ValueWrapper get(Object key) {
        Object data = lookup(genKey(key));
        return data == null ? null : new SimpleValueWrapper(data);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        return (T) lookup(genKey(key));
    }

    @Override
    public void put(Object key, Object value) {
        // evict if put a null value
        if (value == null) {
            evict(key);
            return;
        }

        save(genKey(key), value);
    }

    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
        ValueWrapper old = get(key);
        if (old == null)
            put(key, value);
        return old;
    }

    @Override
    public void evict(Object key) {
        delete(genKey(key));
    }

    @Override
    public void clear() {
        deleteAll();
    }

    // TODO 针对下面方法中可能发生的异常应考虑合适的处理方式,不应仅仅打印日志
    // TODO 思考操作分布式缓存失败时,可能发生什么,如何降低数据不一致的概率

    /**
     * 通过 xmemcached 客户端访问 memcached 服务并查询缓存的数据
     *
     * @param key memcached 中的 key
     * @return memcached 中对应 key 的 value 数据
     */
    protected Object lookup(String key) {
        Object data = null;
        try {
            data = memcachedClient.get(key);
        } catch (TimeoutException e) {
            LOGGER.error("Timeout when looking up cached data for key:{}", key, e);
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted when looking up cached data for key:{}", key, e);
        } catch (MemcachedException e) {
            LOGGER.error("Failed when looking up cached data for key:{}", key, e);
        }
        return data;
    }

    /**
     * 通过 xmemcached 客户端访问 memcached 服务并保存数据
{'fraction_non_alphanumeric': 0.09641217480020405, 'fraction_numerical': 0.0020404693079408265, 'mean_word_length': 2.571341833636916, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '376527', 'n_tokens_mistral': 1787, 'n_tokens_neox': 1788, 'n_words': 472}