標籤:object sts trace str byte ons eric 個數 interrupt
需要使用如下jar包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool --> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency>
1.建立串連池
package com.spring.wzy;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtil { /** * 雙重鎖形式的單例 * */ private static volatile JedisPool jedisPool = null; private JedisPoolUtil(){} public static JedisPool getJedisPoolInstance(){ if(null == jedisPool){ synchronized (JedisPoolUtil.class) { if(null == jedisPool){ // GenericObjectPoolConfig poolConfig = new JedisPoolConfig(); JedisPoolConfig poolConfig = new JedisPoolConfig(); // poolConfig.setMaxActive(1000);//最大執行個體數 poolConfig.setMaxWaitMillis(100*1000);//最大等待時間 poolConfig.setMaxIdle(50);//最多空閑執行個體 poolConfig.setTestOnBorrow(true);//獲得一個執行個體時檢查串連可用性 jedisPool = new JedisPool(poolConfig, "192.168.23.128", 6379); } } } return jedisPool; } public static void release(JedisPool jedisPool, Jedis jedis){ if(null != jedis){ //jedis.close(); jedisPool.returnResourceObject(jedis); } }}
2.使用執行個體
public static void main(String[] args) throws InterruptedException { JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance(); Jedis j = null; try{ j = jedisPool.getResource(); // j.select(0);//選中資料庫,預設是0號庫// j.flushAll();//清空資料庫 // j.del("key"); //刪除key // j.set("k1", "v1");// j.set("k2", "v2");// j.set("k2", "v3");//新值會把舊值覆蓋 // System.out.println(j.exists("k2"));//返回ture/false// System.out.println(j.exists("k1","k3"));//返回存在的個數 // System.out.println(new String(j.get("k1".getBytes())));// System.out.println(j.get("k2")); // Set<String> keys = j.keys("*");// for(String k:keys){// System.out.println(k);// } // j.move("k1", 2);//把k1剪下到2號庫 // System.out.println(j.expire("k2", 10));//設定key的存活時間(s),執行成功返回1,否則返回0// Thread.sleep(3000);// System.out.println(j.ttl("k2"));//查看key的到期時間 }catch (Exception e) { e.printStackTrace(); }finally{ JedisPoolUtil.release(jedisPool, j); }
java操作Redis