1.Jedis基本使用

使用Jedis客户端使用Redis服务与在服务器上通过redis-cli使用命令基本一样,关于Redis命令请参考:http://www.redis.cn/commands.html、http://www.runoob.com/redis/redis-commands.html

1.使用Jedis连接Redis服务

publicstaticvoid main(String[] args){Jedis jedis =newJedis("192.168.110.101",6379);String result = jedis.ping();// 测试连接System.out.println(result);    jedis.close();}

2.Jedis客户端的基本使用

下面根据Redis命令划分,使用Jedis

//关键字(Keys) System.out.println("exists :"+ jedis.exists("name"));System.out.println("del :"+ jedis.del("name"));//字符串(String) System.out.println("set :"+ jedis.set("name","危常焕"));System.out.println("get :"+ jedis.get("name"));//哈希(Hashs) for(int i =0; i <10; i++){System.out.println("hset :"+ jedis.hset("hset","set-key"+ i,"set-value"+ i));}System.out.println("hkeys :"+ jedis.hkeys("hset"));//列表(Lists) System.out.println("rpush :"+ jedis.rpush("lset","lset001","lset002","lset003","lset004"));System.out.println("lrange :"+ jedis.lrange("lset",0,2));//集合(Sets)System.out.println("sadd :"+ jedis.sadd("sadd","sadd001","sadd002","sadd003"));System.out.println("scard :"+ jedis.scard("sadd"));//有序集合(Sorted Sets)Map<String,Double> scoreMembers =newHashMap<String,Double>();scoreMembers.put("001",0.1D);scoreMembers.put("002",0.2D);scoreMembers.put("003",0.3D);System.out.println("zadd :"+ jedis.zadd("zadd", scoreMembers));System.out.println("zrange :"+ jedis.zrange("zadd",1L,2L));//HyperLogLog for(int i =0; i <10; i++){System.out.println("pfadd :"+ jedis.pfadd("HyperLogLog", UUID.randomUUID().toString()));}System.out.println("pfcount :"+ jedis.pfcount("HyperLogLog"));//发布/订阅(Pub/Sub)Thread thread =newThread(newRunnable(){@Overridepublicvoid run(){finalJedis j =newJedis("192.168.110.101",6379);        j.subscribe(newJedisPubSub(){@Overridepublicvoid onMessage(String channel,String message){System.out.println("onMessage--channel:"+ channel +" message:"+ message);this.unsubscribe();}},"channel001");        j.close();System.out.println("连接已关闭");}});thread.start();Thread.sleep(10);System.out.println("publish :"+ jedis.publish("channel001","发送一条消息"));//事务(Transactions)Transaction transaction = jedis.multi();System.out.println("set :"+ transaction.set("multi001","123"));System.out.println("incr :"+ transaction.incr("multi001"));System.out.println("transaction.exec :"+ transaction.exec());// 脚本(Scripting) System.out.println("eval :"+ jedis.eval("local msg = \"Hello, world!\" return msg"));//连接(Connection) System.out.println("ping :"+ jedis.ping());System.out.println("select :"+ jedis.select(0));//服务(Server)System.out.println("dbSize :"+ jedis.dbSize());System.out.println("clientList :"+ jedis.clientList());

Redis支持执行Lua脚本,关于Lua脚本的基本使用可参考:

2.Jedis深入使用

1.Jedis中常见类关系如下

redis 连接的客户端工具 redis客户端使用_缓存

2.JedisPool的使用

JedisPool只是提供基本的连接池而已

publicstaticvoid main(String[] args){JedisPoolConfig config =newJedisPoolConfig();// 连接池中最大连接数。高版本:maxTotal,低版本:maxActive    config.setMaxTotal(8);// 连接池中最大空闲的连接数    config.setMaxIdle(4);// 连接池中最少空闲的连接数    config.setMinIdle(1);// 当连接池资源耗尽时,调用者最大阻塞的时间,超时将跑出异常。单位,毫秒数;默认为-1.表示永不超时。高版本:maxWaitMillis,低版本:maxWait    config.setMaxWaitMillis(15000);// 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除    config.setMinEvictableIdleTimeMillis(300000);// 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3    config.setNumTestsPerEvictionRun(3);// “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1    config.setTimeBetweenEvictionRunsMillis(60000);// 一分钟// 向调用者输出“链接”资源时,是否检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取。默认为false。建议保持默认值    config.setTestOnBorrow(false);// 向连接池“归还”链接时,是否检测“链接”对象的有效性。默认为false。建议保持默认值    config.setTestOnReturn(false);// 向调用者输出“链接”对象时,是否检测它的空闲超时;默认为false。如果“链接”空闲超时,将会被移除。建议保持默认值    config.setTestWhileIdle(false);JedisPool pool =newJedisPool(config,"192.168.110.101",6379);Jedis jedis = pool.getResource();// 从pool中获取资源try{        jedis.set("k1","v1");System.out.println(jedis.get("k1"));}catch(Exception e){        e.printStackTrace();}finally{        jedis.close();// pool.returnResource(jedis); // 此方法已过时}for(int i =0; i <10; i++){        jedis = pool.getResource();// jedis.close(); // 去掉注释观察效果System.out.println("NumActive:"+ pool.getNumActive());System.out.println("NumIdle:"+ pool.getNumIdle());System.out.println("NumWaiters:"+ pool.getNumWaiters());}    pool.close();    pool.destroy();}

3.JedisSentinelPool使用

JedisSentinelPool在有Sentinel集群服务时使用,他除了提供连接池功能之外还能够在master服务宕机Sentinel集群选出新的master服务节点后连接池连接的Redis服务也会更新成新的master服务地址

publicstaticvoid main(String[] args){String host =null;int port =0;Set<String> sentinels =newHashSet<String>();    sentinels.add("192.168.110.100:26379");    sentinels.add("192.168.110.100:36379");    sentinels.add("192.168.110.100:46379");JedisSentinelPool jedisSentinelPool =newJedisSentinelPool("master001", sentinels);    host = jedisSentinelPool.getCurrentHostMaster().getHost();    port = jedisSentinelPool.getCurrentHostMaster().getPort();System.out.println(host +":"+ port);Jedis jedis = jedisSentinelPool.getResource();    jedis.set("001","ASDFG");System.out.println(jedis.get("001"));    jedis.close();// 关闭Redis Master服务Scanner scanner =newScanner(System.in);String input = scanner.nextLine();System.out.println(input);    host = jedisSentinelPool.getCurrentHostMaster().getHost();    port = jedisSentinelPool.getCurrentHostMaster().getPort();System.out.println(host +":"+ port);    jedis = jedisSentinelPool.getResource();    jedis.set("001","ZXCVB");System.out.println(jedis.get("001"));    jedis.close();    jedisSentinelPool.close();    jedisSentinelPool.destroy();}

注意:master服务宕机之后一段时间内(若干秒)方法返回的jedis客户端还是以前的master服务地址,会导致连接池在一段时间内(若干秒)不能使用。但是很快就会回复正常连接到新的master服务上,需要注意的是这需要一段时间(若干秒)

运行以上程序输出如下,注意中间打印的部分:

192.168.110.102:6379ASDFG2015-10-222:50:30 redis.clients.jedis.JedisSentinelPool initPool信息:CreatedJedisPool to master at 192.168.110.101:6379192.168.110.101:6379ZXCVB

对于Sentinel的特有操作Jedis类就有方法支持:

redis 连接的客户端工具 redis客户端使用_Redis_02


4.ShardedJedisPool使用

ShardedJedisPool除了有连接池的功能,它可以根据key计算出这个key对应存储的Redis服务器,实现多台Redis服务器扩容

publicstaticvoid main(String[] args){JedisPoolConfig config =newJedisPoolConfig();List<JedisShardInfo> shards =newArrayList<JedisShardInfo>();    shards.add(newJedisShardInfo("192.168.110.101","Redis001",6379,20*1000,1));    shards.add(newJedisShardInfo("192.168.110.102","Redis002",6379,20*1000,2));    shards.add(newJedisShardInfo("192.168.110.103","Redis003",6379,20*1000,4));ShardedJedisPool shardedJedisPool =newShardedJedisPool(config, shards);for(int i =0; i <10; i++){ShardedJedis shardedJedis = shardedJedisPool.getResource();String key ="shard"+ i;        shardedJedis.set(key,"v-"+ i);System.out.println(shardedJedis.get(key));JedisShardInfo shardInfo = shardedJedis.getShardInfo(key);System.out.println("getHost:"+ shardInfo.getHost());        shardedJedis.close();}    shardedJedisPool.close();    shardedJedisPool.destroy();}

运行打印结果:

v-0getHost:192.168.110.102v-1getHost:192.168.110.101v-2getHost:192.168.110.102v-3getHost:192.168.110.103v-4getHost:192.168.110.102v-5getHost:192.168.110.102v-6getHost:192.168.110.103v-7getHost:192.168.110.102v-8getHost:192.168.110.102v-9getHost:192.168.110.103

注意:计算key对应到Redis服务器的默认算法与Redis的IP和端口无关,只与JedisShardInfo的name属性有关,所以可以好好使用这个特性!其具体实现如下:

//位置:redis.clients.util.Sharded<R, S extends ShardInfo<R>>privatevoid initialize(List<S> shards){    nodes =newTreeMap<Long, S>();for(int i =0; i != shards.size();++i){final S shardInfo = shards.get(i);if(shardInfo.getName()==null)for(int n =0; n <160* shardInfo.getWeight(); n++){                nodes.put(this.algo.hash("SHARD-"+ i +"-NODE-"+ n), shardInfo);}elsefor(int n =0; n <160* shardInfo.getWeight(); n++){                nodes.put(this.algo.hash(shardInfo.getName()+"*"+ shardInfo.getWeight()+ n), shardInfo);}        resources.put(shardInfo, shardInfo.createResource());}}

-------------------------------------------------------------------------------------------------------------------------------