標籤:
首先構建非切片串連池jedisPool對象,寫好配置redis串連的方法。
/** * 構建redis切片串連池 * * @param ip * @param port * @return JedisPool */ public static JedisPool getJedisPool() { if (jedisPool == null) { synchronized (lock) { //redis伺服器對應的IP和連接埠 String redisIp = PropertiesUtils.getProperties("REDIS_SERVER_IP"); Integer redisPort = Integer.valueOf(PropertiesUtils.getProperties("REDIS_SERVER_PORT")); if (jedisPool == null) { JedisPoolConfig config = new JedisPoolConfig(); //設定串連池初始化大小和最大容量 // 控制一個pool可分配多少個jedis執行個體,通過pool.getResource()來擷取; // 如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis執行個體,則此時pool的狀態為exhausted(耗盡)。 config.setMaxTotal(-1); // 控制一個pool最多有多少個狀態為idle(閒置)的jedis執行個體。 config.setMaxIdle(1000); // 表示當borrow(引入)一個jedis執行個體時,最大的等待時間,如果超過等待時間,則直接拋出JedisConnectionException; config.setMaxWaitMillis(1000 * 30); // 在borrow一個jedis執行個體時,是否提前進行validate操作;如果為true,則得到的jedis執行個體均是可用的; config.setTestOnBorrow(true); // 寫 jedisPool = new JedisPool(config, redisIp, redisPort,DEFAULT_TIME_OUT); } } } return jedisPool; }
我們都知道redis是key,value型就當它是記憶體資料庫把,雖然一般常用於資料緩衝,畢竟你往記憶體中放幾千萬條資料會弄爆- -(雖然我就是要這麼幹) 下來,根據key擷取value
/** * 擷取資料 * * @param key * @return */ public static String getForString(String key){ List<String> values = mgetForString(key); if(values == null) { return null; } else { return values.get(0); } }
也可根據key擷取value的集合
/** * 擷取資料 * * @param key * @return */ public static List<String> mgetForString(String... key){ List<String> value = null; JedisPool pool = null; Jedis jedis = null; try { pool = getJedisPool(); jedis = pool.getResource(); value = jedis.mget(key); } catch (Exception e) { log.error(e); } finally { //返還到串連池 returnJedisResource(jedis); } return value; }
將資料載入到redis中的方法 一般是用set. 如下列方法,這裡指定value是String類型,也是因為我的業務關係把value轉成了json串~
public static void setForString(String key,String value){ JedisPool pool = null; Jedis jedis = null; try { pool = getJedisPool(); jedis = pool.getResource(); jedis.set(key, value); } catch (Exception e) { log.error(e); } finally { //返還到串連池 returnJedisResource(jedis); } }
也可擷取雜湊結構的欄位和值
/** * 設定雜湊結構的欄位和值 * @param key * @param value */ public static void setForHashObj(String key, Map<String, String> value) { JedisPool pool = null; Jedis jedis = null; try { pool = getJedisPool(); jedis = pool.getResource(); jedis.hmset(key, value); } catch (Exception e) { log.error(e); } finally { // 返還到串連池 returnJedisResource(jedis); } }
這裡的Map也可以改為List<Map<String, String>> values,其實一樣的~然後再遍曆這個Map即可~
Redis常用方法