All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nutz.plugins.cache.impl.redis.RedisCache2 Maven / Gradle / Ivy

There is a newer version: 1.r.69.v20220215
Show newest version
package org.nutz.plugins.cache.impl.redis;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import org.nutz.lang.Streams;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.plugins.cache.impl.lcache.LCacheManager;

import redis.clients.jedis.Jedis;

@SuppressWarnings("unchecked")
public class RedisCache2 extends RedisCache {

    private static final Log log = Logs.get();

    private String name;

    public RedisCache2 setName(String name) {
        this.name = name;
        return this;
    }

    @Override
    public V get(K key) {
        if (debug)
            log.debugf("GET key=%s:%s", name, key);
        Jedis jedis = null;
        byte[] buf = null;
        try {
            jedis = LCacheManager.me().jedis();
            buf = jedis.get(genKey(key));
            if (buf == null)
                return null;
            return (V) serializer.toObject(buf);
        } finally {
            Streams.safeClose(jedis);
        }
    }

    @Override
    public V put(K key, V value) {
        if (debug)
            log.debugf("SET key=%s:%s", name, key);
        Jedis jedis = null;
        try {
            jedis = LCacheManager.me().jedis();
            byte[] buf = (byte[])serializer.fromObject(value);
            if (ttl > 0)
                jedis.setex(genKey(key), ttl, buf);
            else
                jedis.set(genKey(key), buf);
            return null;
        } finally {
            Streams.safeClose(jedis);
        }
    }

    @Override
    public V remove(K key) {
        if (debug)
            log.debugf("DEL key=%s:%s", name, key);
        Jedis jedis = null;
        try {
            jedis = LCacheManager.me().jedis();
            jedis.del(genKey(key));
            return null;
        } finally {
            Streams.safeClose(jedis);
        }
    }

    public void clear() {
        if (debug)
            log.debugf("CLR name=%s", name);
        for (K key : keys()) {
            remove(key);
        }
    }

    public int size() {
        if (debug)
            log.debugf("SIZ name=%s", name);
        return keys().size();
    }

    public Set keys() {
        if (debug)
            log.debugf("KEYS name=%s", name);
        Jedis jedis = null;
        try {
            jedis = LCacheManager.me().jedis();
            return (Set) jedis.keys(name + ":*");
        } finally {
            Streams.safeClose(jedis);
        }
    }

    public Collection values() {
        if (debug)
            log.debugf("VLES name=%s", name);
        return Collections.EMPTY_LIST;
    }
    
    protected byte[] genKey(Object key) {
        return (name + ":" + key).getBytes();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy