idearedis是基于Redis的Java客户端,提供了连接池、线程池、分片等丰富的功能,简化了对Redis的操作。
一、使用
使用idearedis前,需要在maven文件中加入如下依赖:
<dependency>
<groupId>com.github.xdiamond</groupId>
<artifactId>idearedis</artifactId>
<version>0.1.0-RELEASE</version>
</dependency>
连接Redis:
RedisClient client = new RedisClient("localhost", 6379);
RedisConnection conn = client.connect();
使用完后,需要关闭连接:
conn.close();
client.shutdown();
二、连接池
使用连接池可以避免频繁地创建、关闭连接,提高性能。 创建连接池:
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(100);
poolConfig.setMaxIdle(50);
poolConfig.setMinIdle(10);
poolConfig.setMaxWaitMillis(5000);
JedisPool pool = new JedisPool(poolConfig, "localhost", 6379);
从连接池中获取连接:
RedisConnection conn = RedisConnectionUtils.getConnection(pool);
使用完后,需要将连接返回到连接池:
RedisConnectionUtils.releaseConnection(conn, pool);
三、线程池
使用线程池可以在高并发情况下提高系统处理能力。 创建线程池:
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(100));
将Redis操作任务加入线程池:
threadPool.submit(new Runnable() {
public void run() {
//Redis操作
}
});
关闭线程池:
threadPool.shutdown();
四、分片
在分布式情况下,单个Redis服务器容量可能无法满足需求,可以将数据分为多份存储在不同的Redis服务器上。 使用JedisCluster可以简化使用Redis集群的操作,实现分片功能。 创建JedisCluster:
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7000));
jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7001));
jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7002));
JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes);
操作Redis:
jedisCluster.set("foo", "bar");
jedisCluster.get("foo");
关闭JedisCluster:
jedisCluster.close();