Java操作Redis
使用连接池
1 public class Test { 2 3 /** 4 * Redis地址 5 */ 6 private static final String ADDR = "10.124.133.184"; 7 8 /** 9 * Redis端口 10 */ 11 private static final Integer PORT = 6379; 12 13 /** 14 * Redis访问密码 15 */ 16 private static final String AUTH = "icloud20180514160728"; 17 18 /** 19 * 可用连接实例的最大数目,默认值为8 20 * 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽) 21 */ 22 private static final Integer MAX_ACTIVE = 1024; 23 24 /** 25 * 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 26 */ 27 private static final Integer MAX_IDLE = 200; 28 29 /** 30 * 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; 31 */ 32 private static int MAX_WAIT = 10000; 33 34 private static final Integer TIMEOUT = 10000; 35 36 /** 37 * 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 38 */ 39 private static final Boolean TEST_ON_BORROW = true; 40 41 private static JedisPool jedisPool = null; 42 43 44 /** 45 * 初始化Redis连接池 46 */ 47 static { 48 try { 49 JedisPoolConfig config = new JedisPoolConfig(); 50 config.setMaxIdle(MAX_IDLE); 51 config.setTestOnBorrow(TEST_ON_BORROW); 52 jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); 53 } catch (Exception e) { 54 e.printStackTrace(); 55 } 56 } 57 58 /** 59 * 获取Jedis实例 60 * @return 61 */ 62 private static synchronized Jedis getJedis() { 63 try { 64 if (jedisPool != null) { 65 return jedisPool.getResource(); 66 } else { 67 return null; 68 } 69 } catch (Exception e) { 70 e.printStackTrace(); 71 return null; 72 } 73 } 74 public static void main(String[] args) { 75 76 Jedis jedis = null; 77 jedis = getJedis(); 78 if(null != jedis){ 79 List<String> configList = jedis.configGet("*"); 80 Map<String, String> confMap = new HashMap<String, String>(); 81 Integer step = 2; 82 for(int i = 0; i < configList.size(); i = i + step){ 83 String paramName = configList.get(i); 84 String paramValue = configList.get(i + 1); 85 confMap.put(paramName, paramValue); 86 } 87 jedis.close(); 88 }else{ 89 System.out.println("jedis is null"); 90 } 91 } 92 }
不用连接池
public static void main(String[] args) { Jedis jedis = null; jedis = new Jedis(ADDR, PORT); jedis.auth(AUTH); Map<String, String> confMap = new HashMap<String, String>(); List<String> configList = jedis.configGet("*"); Integer step = 2; for(int i = 0; i < configList.size(); i = i + step){ String paramName = configList.get(i); String paramValue = configList.get(i + 1); confMap.put(paramName, paramValue); } for(Map.Entry entry : confMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // jedis.configSet("hash-max-ziplist-entries","256"); System.out.println("hash-max-ziplist-entries: " + jedis.configGet("hash-max-ziplist-entries")); jedis.close(); }