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

gu.sql2java.redis.cache.RedisCacheReader Maven / Gradle / Ivy

There is a newer version: 5.3.3
Show newest version
package gu.sql2java.redis.cache;

import gu.simplemq.Channel;
import gu.simplemq.redis.JedisPoolLazy;
import gu.simplemq.redis.RedisFactory;
import gu.simplemq.redis.RedisTable;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
import static gu.sql2java.redis.cache.RedisCaches.getCacheKeyPrefix;


/**
 * 基于REDIS的数据库表记录缓存访问实现用于读取{@link RedisCache}保存在REDIS中的数据
 * @author guyadong
 *
 */
public class RedisCacheReader{
	private final RedisTable table;
	private final Channel channel;
	/**
	 * 构造方法
	 * @param keyPrefix KEY的统一前缀,为{@code null}或空使用默认值{@link RedisCaches#getCacheKeyPrefix() }
	 * @param beanClassName 数据库记录对象
	 * @param columnName 用作REDIS key的字段名
	 */
	RedisCacheReader(String keyPrefix,String beanClassName,String columnName) {
		if(isNullOrEmpty(keyPrefix)){
			keyPrefix = getCacheKeyPrefix();
		}
		checkArgument(!isNullOrEmpty(beanClassName),"beanClassName is null or empty");
		checkArgument(!isNullOrEmpty(columnName),"columnName is null or empty");
		String channelName = RedisCaches.channelNameOf(keyPrefix, beanClassName, columnName);
		channel = new Channel<>(channelName, JSONObject.class);
		table =  RedisFactory.getTable(channel, JedisPoolLazy.getDefaultInstance());
	}
	/**
	 * 构造方法
	 * @param beanClassName 数据库记录对象
	 * @param columnName 用作REDIS key的字段名
	 */
	RedisCacheReader(String beanClassName,String columnName) {
		this(null, beanClassName, columnName);
	}

	/**
	 * 返回主键或索引键返回指定的数据库记录对象
	 * @param key
	 */
	public JSONObject get(Object key) {
		return table.get(String.valueOf(key));
	}

	public Map get(String... keys) {
		return table.get(keys);
	}
	/**
	 * 以T-JSON映射形式返回主键或索引键返回指定的数据库记录对象
	 * @param keys
	 */
	@SuppressWarnings("unchecked")
	public  Map get(T... keys) {
		ArrayList keyList = Lists.newArrayList(Iterables.filter(Arrays.asList(keys),Predicates.notNull()));
		String[] transKeys = Lists.transform(keyList, String::valueOf).toArray(new String[0]);
		Map m = table.get(transKeys);
		Map tmMap= Maps.newHashMap();
		JSONObject v;
		for(T k : keyList){
			if(null != (v = m.get(String.valueOf(k)))){
				tmMap.put(k, v);
			}
		}
		return tmMap;
	}

	public int foreach(Predicate action) {
		return table.foreach(null, action);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy