Redis中JedisPool基本使用

来源:互联网 发布:分型指标源码 编辑:程序博客网 时间:2024/05/17 04:39

public class PropertiesUtils {public PropertiesUtils() {}private static Properties props = new Properties();static {try {props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/redis.properties"));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static String getValue(String key) {return props.getProperty(key);}public static void updateProperties(String key, String value) {props.setProperty(key, value);}}public class JedisClientPool {public static JedisClientPool jedisClientPool = getInstance();public static JedisPool jedisPool;public static int maxTotal;public static int maxIdle;public static int maxWaitMillis;public static synchronized JedisClientPool getInstance() {if (null == jedisClientPool) {jedisClientPool = new JedisClientPool();}return jedisClientPool;}public JedisClientPool() {if (null == jedisPool) {init();}}/*** 初始化Jedis* @return*/private static JedisPoolConfig initPoolConfig() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();// #最大分配的对象数  :控制一个pool最多有多少个状态为idle的jedis实例jedisPoolConfig.setMaxTotal(maxTotal);//控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)jedisPoolConfig.setMaxIdle(maxIdle);// 当池内没有返回对象时,最大等待时间 : 超时时间jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);// 当调用borrow Object方法时,是否进行有效性检查: 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;jedisPoolConfig.setTestOnBorrow(true);// 当调用return Object方法时,是否进行有效性检查 :在还给pool时,是否提前进行validate操作jedisPoolConfig.setTestOnReturn(true);return jedisPoolConfig;}/*** 初始化jedis连接池*/public static void init() {maxTotal = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxTotal"));maxIdle = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxIdle"));maxWaitMillis = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxWaitMillis"));JedisPoolConfig jedisPoolConfig = initPoolConfig();String host = PropertiesUtils.getValue("redis.host");// "localhost";int port = Integer.parseInt(PropertiesUtils.getValue("redis.port"));// 6379;int timeout = Integer.parseInt(PropertiesUtils.getValue("redis.timeout"));// 60000;//构造连接池jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);}}public class JedisUtil {/**      * 判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty      *       * @param obj      * @return      */      public static boolean isNullOrEmpty(Object obj) {          if (obj == null)              return true;            if (obj instanceof CharSequence)              return ((CharSequence) obj).length() == 0;            if (obj instanceof Collection)              return ((Collection) obj).isEmpty();            if (obj instanceof Map)              return ((Map) obj).isEmpty();            if (obj instanceof Object[]) {              Object[] object = (Object[]) obj;              if (object.length == 0) {                  return true;              }              boolean empty = true;              for (int i = 0; i < object.length; i++) {                  if (!isNullOrEmpty(object[i])) {                      empty = false;                      break;                  }              }              return empty;          }          return false;      }         /**     * 对象转字节数组     * @param object     * @return     */    public static byte[] serialize(Object object) {        ObjectOutputStream oos = null;         ByteArrayOutputStream baos = null;         try {              // 序列化             baos = new ByteArrayOutputStream();             oos = new ObjectOutputStream(baos);             oos.writeObject(object);              byte[] bytes = baos.toByteArray();              return bytes;        } catch (Exception e) {        }         return null;  }    /**     * 字节数组转对象     * @param bytes     * @return     */    public static Object unserialize( byte[] bytes) {        ByteArrayInputStream bais = null;         try {              // 反序列化             bais = new ByteArrayInputStream(bytes);             ObjectInputStream ois = new ObjectInputStream(bais);              return ois.readObject();        } catch (Exception e) {        }         return null;  }        }@SuppressWarnings({"deprecation","rawtypes"})public class JedisClient {public static final Logger log = Logger.getLogger(JedisClient.class);    /**     * 字符串增加     * @param key     * @param value     */public static void addString(String key ,String value){    Jedis redisClient = null;        try {        redisClient = JedisClientPool.jedisPool.getResource();            value = JedisUtil.isNullOrEmpty(value) ? "" : value;              redisClient.set(key,value);          } catch (Exception e) {          // 销毁对象        JedisClientPool.jedisPool.returnBrokenResource(redisClient);        }  finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}    }        /**      * 获取String值      * @param key      * @return value      */     public static String getString(String key){    Jedis redisClient = null;        try {        redisClient = JedisClientPool.jedisPool.getResource();                      return redisClient.get(key);        } catch (Exception e) {          // 销毁对象        JedisClientPool.jedisPool.returnBrokenResource(redisClient);        }  finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}        return null;    }  /*** 保存数据 类型为 Map* @param flag* @param mapData*/public static void setMapDataToRedis(String flag,Map<String, String> mapData) {Jedis redisClient = null;try {redisClient = JedisClientPool.jedisPool.getResource();redisClient.hmset(flag, mapData);} catch (Exception e) {// 销毁对象JedisClientPool.jedisPool.returnBrokenResource(redisClient);} finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}}/*** 保存数据 类型为 key-value* @param flag* @param field* @param value*/public static void setDataToRedis(String flag, String field, String value) {Jedis redisClient = null;try {redisClient = JedisClientPool.jedisPool.getResource();redisClient.hset(flag, field, value);} catch (Exception e) {// 销毁对象JedisClientPool.jedisPool.returnBrokenResource(redisClient);} finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}}/*** 获取Map数据* @param flag* @return*/public static Map<String, String> getMapData(String key) {Map<String, String> dataMap = null;Jedis redisClient = null;try {redisClient = JedisClientPool.jedisPool.getResource();dataMap = redisClient.hgetAll(key);} catch (Exception e) {// 销毁对象JedisClientPool.jedisPool.returnBrokenResource(redisClient);} finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}return dataMap;}/*** 删除* @param flag* @return*/public static long deleteData(String key) {long result = 0;Jedis redisClient = null;try {redisClient = JedisClientPool.jedisPool.getResource();result = redisClient.del(key);} catch (Exception e) {// 销毁对象JedisClientPool.jedisPool.returnBrokenResource(redisClient);} finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}return result;}/*** 根据key和字段获取数据* @param flag* @param field* @return*/public static String getData(String key, String value) {String data = null;Jedis redisClient = null;try {redisClient = JedisClientPool.jedisPool.getResource();data = redisClient.hget(key, value);} catch (Exception e) {// 销毁对象JedisClientPool.jedisPool.returnBrokenResource(redisClient);} finally {// 还原到连接池JedisClientPool.jedisPool.returnResource(redisClient);}return data;}//String 测试@Testpublic void testString(){Jedis redis = JedisClientPool.jedisPool.getResource();redis.set("str1","str_values1");System.out.println(redis.get("str1"));//显示所有值Set keys = redis.keys("*");//列出所有的key    Iterator it=keys.iterator() ;      while(it.hasNext()){          Object obj1 = it.next();          System.out.println(obj1);      }   }//list 测试@Testpublic void testList() {Jedis redis = JedisClientPool.jedisPool.getResource();// hset key field value将哈希表key中的域field的值设为value。redis.hset("list", "field1", "value1");redis.hset("list", "field2", "value2");redis.hset("list", "field3", "value3");SearchKeyWord searchKeyWord = new SearchKeyWord();searchKeyWord.setKeyWordsName("java");searchKeyWord.setKeyWordsCount(String.valueOf(1));redis.set("obj".getBytes(), JedisUtil.serialize(searchKeyWord));byte[] value = redis.get( "obj".getBytes());Object object = JedisUtil.unserialize(value);                   if(object!= null){            System. out.println(searchKeyWord.getKeyWordsName());       }// 返回哈希表key中,一个或多个给定域的值。List<String> list = redis.hmget("list", "field1", "field2", "field3");if(redis.exists("list")){System.out.println("存在");}for (String tmp : list) {System.out.println(tmp);}}//map 测试@Testpublic void testMap() {// 同时将多个field - value(域-值)对设置到哈希表key中。Map<String, String> map = new ConcurrentHashMap<String, String>();for (int i = 0; i < 10000; i++) {map.put("field" + i, "value" + i);}if (null != getData("table", "field1")) {deleteData("map");}// 得到map下面的username的值setMapDataToRedis("map", map);Map<String, String> maps = getMapData("map");for (String key : maps.keySet()) {  System.out.println("key= "+ key + " and value= " + map.get(key)); }System.out.println(maps.size());}public static void main(String[] args) {// Jedis jedis = new Jedis("127.0.0.1", 6379);Jedis redisClient = JedisClientPool.jedisPool.getResource();        //权限认证redisClient.auth("aaaaa");redisClient.set("bb", "bb");       }}参考 http://www.tuicool.com/articles/vYVvQbyhttp://huangzixun.iteye.com/blog/1871495


0 0
原创粉丝点击