package com.jianfeitech.utils; import java.util.Set; import org.apache.log4j.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import com.jianfeitech.constants.AdConstants; /** * * Redis 工具类。 * * @author wjxie * */ public class RedisUtil { private static Logger logger = Logger.getLogger(RedisUtil.class); private static JedisPool pool; static { pool = new JedisPool(new JedisPoolConfig(), AdConstants.REDIS_URL); } public static String get(String key) { Jedis jedis = getJedis(); try { String result = jedis.get(key); pool.returnResource(jedis); return result; } catch (Exception e) { logger.error("", e); pool.returnBrokenResource(jedis); return null; } } public static void set(String key, String value) { Jedis jedis = getJedis(); try { jedis.set(key, value); pool.returnResource(jedis); } catch (Exception e) { logger.error("", e); pool.returnBrokenResource(jedis); } } public static Long incr(String key) { Jedis jedis = getJedis(); try { Long result = jedis.incr(key); pool.returnResource(jedis); return result; } catch (Exception e) { logger.error("", e); pool.returnBrokenResource(jedis); return null; } } public static void deleteBatch(String pattern) { Jedis jedis = getJedis(); try { Set<String> keys = jedis.keys(pattern); if (keys != null && keys.size() > 0) { for (String key : keys) { jedis.del(key); } } pool.returnResource(jedis); } catch (Exception e) { logger.error("", e); pool.returnBrokenResource(jedis); } } public static Long getLong(String key) { try { String result = get(key); return Long.valueOf(result); } catch (NumberFormatException e) { logger.debug("", e); return 0L; } } public static void setLong(String key, Long value) { String result = String.valueOf(value); set(key, result); } public static Jedis getJedis() { Jedis jedis = null; int count = 0; do { try { jedis = pool.getResource(); } catch (Exception e) { logger.debug("", e); pool.returnBrokenResource(jedis); } count++; } while (jedis == null && count < 10000); if (jedis == null) { throw new RuntimeException("Fucking jedis config."); } return jedis; } }
RedisUtil
猜你喜欢
转载自dsxwjhf.iteye.com/blog/2221044
今日推荐
周排行