一些使用的代码
单个服务
这个例子简单地使用连接池对Jedis连接进行管理,适用于单个Redis服务的情况:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class Sample01 { public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxActive(100); poolConfig.setMaxIdle(50); poolConfig.setMaxWait(3000); poolConfig.setMinIdle(10); JedisPool pool = new JedisPool(poolConfig, "10.10.10.1", 6379); String result = pool.getResource().lpop("testQueue"); System.out.println(result); } } |
服务集群
这个例子适用于多台Redis同时提供服务的情况,通过一致性hash,将数据均匀分布到多台服务上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.ArrayList; import java.util.List; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedisPool; public class Sample02 { public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxActive(100); poolConfig.setMaxIdle(50); poolConfig.setMaxWait(3000); poolConfig.setMinIdle(10); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); shards.add(new JedisShardInfo("10.10.10.1", 6379)); shards.add(new JedisShardInfo("10.10.10.1", 6380)); shards.add(new JedisShardInfo("10.10.10.1", 6381)); ShardedJedisPool pool = new ShardedJedisPool(poolConfig, shards); String result = pool.getResource().lpop("testQueue"); System.out.println(result); } } |
一些用法
从连接池获取的资源如果过期,需要调用pool.returnResource(jedis)
另行处理,并且加入重试机制,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public String rpop(String key) throws Exception { String result = null; ShardedJedis jedis = null; Exception exc = null; for (int times = 0; times < ERROR_TIMES ;times++) { try { jedis = pool.getResource(); result = jedis.rpop(key); } catch (Exception e){ exc = e; logger.error("连接Redis超时,第"+(times+1)+"尝试...",e); pool.returnBrokenResource(jedis); Thread.sleep(100); continue; } finally { pool.returnResource(jedis); } return result; } throw new Exception(exc); } |