Java maven项目整合Redis

来源:互联网 发布:手机淘宝 天天特价 编辑:程序博客网 时间:2024/05/17 15:02

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 redisredis.pool.maxActive=512redis.pool.maxIdle=100redis.pool.maxWait=100000redis.pool.testOnBorrow=trueredis.pool.testOnReturn=trueredis.ip=172.17.6.148redis.port=6379redis.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查询和插入数据的操作,在使用的时候直接调用就行了。

如果没有合适的方法,可以在帮助类中自己添加。

1 0
原创粉丝点击