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

cc.protea.foundation.integrations.RedisUtil Maven / Gradle / Ivy

Go to download

Integrate compatible versions of many external systems to create a REST/HTTP server foundation

There is a newer version: 0.5.12
Show newest version
package cc.protea.foundation.integrations;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisException;

public class RedisUtil {

	static JedisPool pool;
	static Logger log = LoggerFactory.getLogger(RedisUtil.class);

	static {
		RedisUtil.pool = RedisUtil.getPool();
	}

	private static JedisPool getPool() {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(64);
			config.setMinIdle(3);
	        URI redisUri = new URI(System.getenv("REDISCLOUD_URL"));
	        return new JedisPool(config, redisUri.getHost(), redisUri.getPort(), Protocol.DEFAULT_TIMEOUT, redisUri.getUserInfo().split(":",2)[1]);
		} catch (URISyntaxException e) {
	        RedisUtil.log.error("Could not connect to Jedis", e);
	        return null;
		}
	}

	// Basic commands

	public static String set(final String key, final Object value) {
		return RedisUtil.set(key, JsonUtil.toJson(value));
	}

	public static String set(final String key, final Object value, boolean compress) {
		if (compress) {
			return RedisUtil.execute(new WithJedis() { public String process(final Jedis jedis) {
				return jedis.set(key.getBytes(), JsonUtil.toGZippedJson(value));
			}});
		}
		return RedisUtil.set(key, JsonUtil.toJson(value));
	}

	public static String set(final String key, final String value) {
		return RedisUtil.execute(new WithJedis() { public String process(final Jedis jedis) {
			return jedis.set(key, value);
		}});
	}
	public static void setex(final String key, final int expirationSeconds, final Object value) {
		RedisUtil.setex(key, expirationSeconds, JsonUtil.toJson(value));
	}

	public static void setex(final String key, final int expirationSeconds, final String value) {
		RedisUtil.execute(new WithJedis() { public Object process(final Jedis jedis) {
			jedis.setex(key, expirationSeconds, value);
			return null;
		}});
	}

	public static void hset(final String key, String field, final Object value) {
		RedisUtil.hset(key, field, JsonUtil.toJson(value));
	}

	public static void hset(final String key, final String field, final String value) {
		RedisUtil.execute(new WithJedis() { public Object process(final Jedis jedis) {
			jedis.hset(key, field, value);
			return null;
		}});
	}

	public static Long del(final String key) {
		return RedisUtil.execute(new WithJedis() { public Long process(final Jedis jedis) {
			return jedis.del(key);
		}});
	}

	public static String get(final String key) {
		return RedisUtil.execute(new WithJedis() { public String process(final Jedis jedis) {
			return jedis.get(key);
		}});
	}

	public static  T get(final String key, final Class valueType) {
		return RedisUtil.execute(new WithJedis() { public T process(final Jedis jedis) {
			byte[] json = jedis.get(key.getBytes());
			return JsonUtil.fromJson(json, valueType);
		}});
	}
	
	public static  T get(final String key, final TypeReference valueType) {
		return RedisUtil.execute(new WithJedis() { public T process(final Jedis jedis) {
			String json = jedis.get(key);
			return JsonUtil.fromJson(json, valueType);
		}});
	}
	
	public static String hget(final String key, final String field) {
		return RedisUtil.execute(new WithJedis() { public String process(final Jedis jedis) {
			return jedis.hget(key, field);
		}});
	}

	public static  T hget(final String key, final String field, final Class valueType) {
		return RedisUtil.execute(new WithJedis() { public T process(final Jedis jedis) {
			String json = jedis.hget(key, field);
			return JsonUtil.fromJson(json, valueType);
		}});
	}
	
	public static Map hgetAll(final String key) {
		return RedisUtil.execute(new WithJedis>() { public Map process(final Jedis jedis) {
			return jedis.hgetAll(key);
		}});
	}

	public static  Map hgetAll(final String key, final String field, final Class valueType) {
		Map raw = hgetAll(key);
		Map all = new HashMap<>();
		for(Entry entry : raw.entrySet()) {
			all.put(entry.getKey(), JsonUtil.fromJson(entry.getValue(), valueType));
		}
		//raw.forEach((k,v)-> all.put(k, JsonUtil.fromJson(v, valueType)));
		return all;
	}


	// For more advanced work

	public static interface WithJedis  {
	    public T process(Jedis jedis);
	}

	public static interface WithPipeline {
	    public void process(Pipeline pipeline);
	}

	public static interface WithJedisNull {
	    public void process(Jedis jedis);
	}

	public static interface WithTransaction {
		public void process(Transaction transaction);
	}

	public static List transaction(final WithTransaction cb) {
		Jedis jedis = RedisUtil.pool.getResource();
		boolean returned = false;
		try {
			Transaction t = jedis.multi();
			cb.process(t);
			return t.exec();
		} catch (JedisException e) {
			RedisUtil.pool.returnBrokenResource(jedis);
			returned = true;
			throw e;
		} finally {
			if (!returned) {
				RedisUtil.pool.returnResource(jedis);
			}
		}
	}

	public static void redis(final WithJedisNull cb) {
		RedisUtil.jedis(cb);
	}

	public static void jedis(final WithJedisNull cb) {
		Jedis jedis = RedisUtil.pool.getResource();
		boolean returned = false;
		try {
			cb.process(jedis);
		} catch (JedisException e) {
			RedisUtil.pool.returnBrokenResource(jedis);
			returned = true;
			throw e;
		} finally {
			if (!returned) {
				RedisUtil.pool.returnResource(jedis);
			}
		}
	}

	public static void pipeline(final WithPipeline wp) {
		Jedis jedis = RedisUtil.pool.getResource();
		boolean doReturn = true;
		try {
			Pipeline p = jedis.pipelined();
			wp.process(p);
			p.sync();
		} catch (JedisException e) {
			RedisUtil.pool.returnBrokenResource(jedis);
			doReturn = false;
			throw e;
		} finally {
			if (doReturn) {
				RedisUtil.pool.returnResource(jedis);
			}
		}
	}

	public static  T execute(final WithJedis  cb) {
		Jedis jedis = RedisUtil.pool.getResource();
		boolean doReturn = true;
		try {
			return cb.process(jedis);
		} catch (JedisException e) {
			RedisUtil.pool.returnBrokenResource(jedis);
			doReturn = false;
			throw e;
		} finally {
			if (doReturn) {
				RedisUtil.pool.returnResource(jedis);
			}
		}
	}

	// Utilities

	public static Integer getInteger(final Map map, final String key) {
		if (map == null || ! map.containsKey(key)) {
			return null;
		}
		String value = map.get(key);
		return StringUtils.isNumeric(value) ? Integer.valueOf(value) : null;
	}

	static String dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";

	public static String toDate(final Date in) {
		return new SimpleDateFormat(RedisUtil.dateFormat).format(in);
	}

	public static Date toDate(final String in) {
		if (in == null) {
			return null;
		}
		try {
			return new SimpleDateFormat(RedisUtil.dateFormat).parse(in);
		} catch (ParseException e) {
			return null;
		}
	}

	public static List asList(final Set set) {
		List list = new ArrayList();
		if (set == null) {
			return list;
		}
		list.addAll(set);
		return list;
	}
}