Java maven項目整合Redis

1、爲什麼要使用Redis?

Redis是一個key-value存儲系統。主要用於解決分佈式系統中的多臺主從機之間的數據同步和共享問題。

2、Redis有哪些特點?

1)、redis的數據完全存儲在內存中,使用磁盤只用於持久性,所以redis的速度非常快;

2)、相比許多鍵值存儲系統,redis擁有較爲豐富的數據類型;

3)、redis的操作都是原子性的,所以在異步的時候也是安全的;

4)、redis可以將數據複製到任意數量的從機。

3、如何將redis整合到項目中?(默認redis已經安裝好了)

1)、pom文件中引入相關包

         <dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>


2)、redis配置

#config for redis
redis.pool.maxActive=512
redis.pool.maxIdle=100
redis.pool.maxWait=100000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.ip=172.17.6.148
redis.port=6379
redis.expire=1200

3)、封裝redis幫助類

public class RedisProvider {

	protected static final Logger LOG = LoggerFactory.getLogger(RedisProvider.class);
	protected static JedisPool jedispool;
	protected static int EXPIRE = 130;
	static{
		ResourceBundle bundle = ResourceBundle.getBundle("redis");
        if (bundle == null) {
            throw new IllegalArgumentException(
                    "[redis.properties] is not found!");
        }

        EXPIRE = Integer.valueOf(bundle.getString("redis.expire"));
        
        JedisPoolConfig jedisconfig = new JedisPoolConfig();
        jedisconfig.setMaxActive(Integer.valueOf(bundle
                .getString("redis.pool.maxActive")));
        jedisconfig.setMaxIdle(Integer.valueOf(bundle
                .getString("redis.pool.maxIdle")));
        jedisconfig.setMaxWait(Long.valueOf(bundle
                .getString("redis.pool.maxWait")));
        jedisconfig.setTestOnBorrow(Boolean.valueOf(bundle
                .getString("redis.pool.testOnBorrow")));
        jedisconfig.setTestOnReturn(Boolean.valueOf(bundle
                .getString("redis.pool.testOnReturn")));
        jedispool = new JedisPool(jedisconfig, bundle.getString("redis.ip"),
                Integer.valueOf(bundle.getString("redis.port")), 100000);
	}
	
	public static Jedis getJedis() {
        Jedis jedis = null;
        try {
            jedis = jedispool.getResource();
        } catch (JedisConnectionException jce) {
            ExceptionUtil.getTrace(jce);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                ExceptionUtil.getTrace(e);
            }
            jedis = jedispool.getResource();
        }
        return jedis;
    }

    public static void returnResource(JedisPool pool, Jedis jedis) {
        if (jedis != null) {
            pool.returnResource(jedis);
        }
    }
}

public class RedisHelper extends RedisProvider{

	/**
	 * Set the string value as value of the key. Default settings at save
	 * time(2000s)
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static String set(String key, String value) {
		Jedis jedis = null;
		String rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.setex(key, EXPIRE, value);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	public static String set2(String key, String value) {
		Jedis jedis = null;
		String rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.setex(key, 360000, value);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * Get the value of the specified key.
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		Jedis jedis = null;
		String rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.get(key);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * Get the values of all the specified keys
	 * 
	 * @param keys
	 * @return
	 */
	public static List<String> mget(String... keys) {
		Jedis jedis = null;
		List<String> rtn = new ArrayList<String>();
		try {
			jedis = getJedis();
			rtn = jedis.mget(keys);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * Set the the respective keys to the respective values.
	 * 
	 * @param keysvalues
	 * @return
	 */
	public static String mset(String... keysvalues) {
		Jedis jedis = null;
		String rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.mset(keysvalues);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * Return all the fields and associated values in a hash.
	 * 
	 * @param key
	 * @return
	 */
	public static Map<String, String> hgetall(String key) {
		Jedis jedis = null;
		Map<String, String> rtn = Maps.newHashMap();
		try {
			jedis = getJedis();
			rtn = jedis.hgetAll(key);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * Set the specified hash field to the specified value.
	 * 
	 * @param key
	 * @param field
	 * @param value
	 * @return
	 */
	public static Long hset(String key, String field, String value) {

		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hset(key, field, value);
			jedis.expire(key, EXPIRE);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * 以map形式存放對象.
	 * 
	 * @param key
	 * @param field
	 * @param obj
	 * @return
	 */
	public static long setObject(String key, String field, Object obj) {
		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hset(key.getBytes(), field.getBytes(),
					ObjectsTranscoder.getObjectsTranscoder().serialize(obj));
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * 獲取對象.
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public static Object getObject(String key, String field) {
		Jedis jedis = null;
		byte[] rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hget(key.getBytes(), field.getBytes());
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return ObjectsTranscoder.getObjectsTranscoder().deserialize(rtn);
	}

	public static void addObject(String key, Object obj) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			jedis.sadd(key.getBytes(), ObjectsTranscoder.getObjectsTranscoder()
					.serialize(obj));
			jedis.expire(key.getBytes(), EXPIRE);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
	}	

	public static List<Object> getAllObject(String key) {
		List<Object> list = new ArrayList<Object>();
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Set<byte[]> set = jedis.smembers(key.getBytes());
			if (set != null && !set.isEmpty()) {
				Iterator<byte[]> it = set.iterator();
				for (; it.hasNext();) {
					byte[] b = it.next();
					Object obj = ObjectsTranscoder.getObjectsTranscoder()
							.deserialize(b);
					list.add(obj);
				}
			}
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return list;
	}

	public static void delAllObject(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			jedis.del(key.getBytes());
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
	}

	public static Long hset2(String key, String field, String value) {

		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hset(key, field, value);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	public static void hdel2(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			jedis.del(key);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
	}

	public static void flush() {
		Jedis jedis = null;
		jedis = getJedis();
		jedis.flushAll();
	}

	public static String hget(String key, String field) {

		Jedis jedis = null;
		String rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hget(key, field);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	public static long hdel(String key, String[] field) {
		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.hdel(key, field);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	public static long mdel(String[] key) {
		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.del(key);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * 設置分佈式鎖
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static long setLock(String key, String value) {
		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.setnx(key, value);
			jedis.expire(key, EXPIRE);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * 釋放鎖
	 * 
	 * @param key
	 * @return
	 */
	public static long delLock(String key) {
		Jedis jedis = null;
		Long rtn = null;
		try {
			jedis = getJedis();
			rtn = jedis.del(key);
		} catch (Exception e) {
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		} finally {
			returnResource(jedispool, jedis);
		}
		return rtn;
	}

	/**
	 * 存儲子調用鏈的list
	 * @param dateKey
	 * @param cidList
	 */
	public static void memoryCid(String dateKey,String cid){
		Jedis jedis = null;
		try {
			jedis = getJedis();
			jedis.sadd(dateKey, cid);
			jedis.expire(dateKey, EXPIRE);
		} catch (Exception e) {
			System.out.println(ExceptionUtil.getTrace(e));
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		}finally {
			returnResource(jedispool, jedis);
		}
	}
	
	/**
	 * 獲取調用鏈list
	 * @param dateKey
	 * @return
	 */
	public static Set<String> getAllCids(String dateKey){
		Jedis jedis = null;
		Set<String> set = null;
		try {
			jedis = getJedis();
			set = jedis.smembers(dateKey);
		} catch (Exception e) {
			System.out.println(ExceptionUtil.getTrace(e));
			LOG.error(ExceptionUtil.getTrace(e));
			jedispool.returnBrokenResource(jedis);
		}finally {
			returnResource(jedispool, jedis);
		}
		return set;
	}
	
}

public class ExceptionUtil {
    public static String getTrace(Throwable throwable) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        throwable.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }
}

在幫助類中,我們封裝了對jedisPool的初始化、獲取jedis連接、釋放連接等操作。

幫助類中封裝了一些常用的redis查詢和插入數據的操作,在使用的時候直接調用就行了。

如果沒有合適的方法,可以在幫助類中自己添加。

發佈了82 篇原創文章 · 獲贊 100 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章