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

com.base4j.cache.store.redis.RedisCache Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
package com.base4j.cache.store.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import com.base4j.cache.CacheException;
import com.base4j.cache.serializer.SerializerTools;
import com.base4j.cache.store.SuperCache;
import com.base4j.cache.store.SuperCacheProvider;
import com.base4j.cache.utils.CacheCodeUtils;
import redis.clients.jedis.Jedis;

/**
 * 缓存的Redis实现
 */
public class RedisCache  extends SuperCache  {
	private String region;
	
	public RedisCache(String region) {
		this.region = region;
	}

	@Override
	public Object gets(Object key) throws CacheException {
		Object result = null;
		// 取得连接实例
		Jedis jedis = SuperCacheProvider.getResource();
		if (jedis == null || StringUtils.isEmpty(key)) {
			return null;
		}
		try {
			// 1.如果确定了返回是字符串类型,就使用这个,但是这样会比较喽
			// 2.如果需要自定义序列化实现使用下面的方法
			byte[] b = jedis.get(SerializerTools.serializeKey(CacheCodeUtils.createRedisKey(region, key)));
			if (b != null) {
				// your serialization utils
				result = SerializerTools.deserializeValue(b);
			}
		} catch (Exception e) {
			// 如果抛出了异常,打印日志并销毁该缓存
			if(e instanceof NullPointerException) {
                evict(key);
            }
		} finally {
			// 造作完成后将连接实例放回到线程池
			SuperCacheProvider.returnResource(jedis);
		}
		return result;
	}

	@Override
	public void put(Object key, Object value) throws CacheException {
		if (value == null) {
            evict(key);
        } else {
			Jedis jedis = SuperCacheProvider.getResource();
			// 将数据保存到缓存容器,1.key序列化,2.value序列化
			try {
				jedis.set(SerializerTools.serializeKey(CacheCodeUtils.createRedisKey(region, key)), SerializerTools.serializeValue(value));
			} catch (Exception e) {
				throw new CacheException(e);
			} finally {
				SuperCacheProvider.returnResource(jedis);
			}
		}
	}

	@Override
	public void evict(Object key) throws CacheException {
		Jedis jedis = SuperCacheProvider.getResource();
		try {
			jedis.del(SerializerTools.serializeKey(CacheCodeUtils.createRedisKey(region, key)));
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			SuperCacheProvider.returnResource(jedis);
		}
	}

	@Override
	public void evict(List keys) throws CacheException {
		if(keys == null || keys.size() == 0) {
            return ;
        }
		Jedis jedis = SuperCacheProvider.getResource();
		String[] theKeys = new String[keys.size()];
		for (int i=0; i listKey = new ArrayList();
		try {
			listKey.addAll(jedis.keys(region+":*"));
			int nKeyPreLen = region.length() + 3;
			for (int i=0; i




© 2015 - 2024 Weber Informatics LLC | Privacy Policy