http://m.blog.csdn.net/koushr/article/details/50956870
連接redis數據庫(非集群模式)
public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大連接數 poolConfig.setMaxTotal(2); // 最大空閑數 poolConfig.setMaxIdle(2); // 最大允許等待時間,如果超過這個時間還未獲取到連接,則會報JedisException異常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); JedisPool pool = new JedisPool(poolConfig, "192.168.83.128", 6379, 0, "123"); Jedis jedis = null; try { for (int i = 0; i < 5; i++) { jedis = pool.getResource(); jedis.set("foo" + i, "bar" + i); System.out.println("第" + (i + 1) + "個連接, 得到的值為" + jedis.get("foo" + i)); // 用完一定要釋放連接 jedis.close(); } } finally { pool.close(); } }
連接redisCluster(集群模式)
public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大連接數 poolConfig.setMaxTotal(1); // 最大空閑數 poolConfig.setMaxIdle(1); // 最大允許等待時間,如果超過這個時間還未獲取到連接,則會報JedisException異常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>(); nodes.add(new HostAndPort("192.168.83.128", 6379)); nodes.add(new HostAndPort("192.168.83.128", 6380)); nodes.add(new HostAndPort("192.168.83.128", 6381)); nodes.add(new HostAndPort("192.168.83.128", 6382)); nodes.add(new HostAndPort("192.168.83.128", 6383)); nodes.add(new HostAndPort("192.168.83.128", 6384)); JedisCluster cluster = new JedisCluster(nodes, poolConfig); String name = cluster.get("name"); System.out.println(name); cluster.set("age", "18"); System.out.println(cluster.get("age")); try { cluster.close(); } catch (IOException e) { e.printStackTrace(); } }