Redis学习十一:Redis的Java客户端Jedis
一、安装 JDK
tar -zxvf jdk-7u67-linux-i586.tar.gz
vi /etc/profile
重启一次 Centos
编码验证
二、安装 eclipse
三、Jedis 所需要的 jar 包
Commons-pool-1.6.jar
Jedis-2.1.0.jar
四、Jedis 常用操作
1. 测试连通性
public class Demo01 { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("127.0.0.1",6379); //查看服务是否运行,打出 pong 表示 OK System.out.println("connection is OK==========>:"+jedis.ping());} }
2.5+1
一个 key
五大数据类型
package com.atguigu.redis.test;import java.util.*;
import redis.clients.jedis.Jedis;
public class Test02
{
public static void main(String[] args)
{Jedis jedis </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Jedis("127.0.0.1",6379<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">key</span> Set<String> keys = jedis.keys("*"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Iterator iterator =<span style="color: rgba(0, 0, 0, 1)"> keys.iterator(); iterator.hasNext();) { String key </span>=<span style="color: rgba(0, 0, 0, 1)"> (String) iterator.next(); System.out.println(key); } System.out.println(</span>"jedis.exists====>"+jedis.exists("k2"<span style="color: rgba(0, 0, 0, 1)">)); System.out.println(jedis.ttl(</span>"k1"<span style="color: rgba(0, 0, 0, 1)">)); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">String </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">jedis.append("k1","myreids");</span> System.out.println(jedis.get("k1"<span style="color: rgba(0, 0, 0, 1)">)); jedis.set(</span>"k4","k4_redis"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(</span>"----------------------------------------"<span style="color: rgba(0, 0, 0, 1)">); jedis.mset(</span>"str1","v1","str2","v2","str3","v3"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(jedis.mget(</span>"str1","str2","str3"<span style="color: rgba(0, 0, 0, 1)">)); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">list</span> System.out.println("----------------------------------------"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">jedis.lpush("mylist","v1","v2","v3","v4","v5");</span> List<String> list = jedis.lrange("mylist",0,-1<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (String element : list) { System.out.println(element); } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">set</span> jedis.sadd("orders","jd001"<span style="color: rgba(0, 0, 0, 1)">); jedis.sadd(</span>"orders","jd002"<span style="color: rgba(0, 0, 0, 1)">); jedis.sadd(</span>"orders","jd003"<span style="color: rgba(0, 0, 0, 1)">); Set</span><String> set1 = jedis.smembers("orders"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Iterator iterator =<span style="color: rgba(0, 0, 0, 1)"> set1.iterator(); iterator.hasNext();) { String string </span>=<span style="color: rgba(0, 0, 0, 1)"> (String) iterator.next(); System.out.println(string); } jedis.srem(</span>"orders","jd002"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(jedis.smembers(</span>"orders"<span style="color: rgba(0, 0, 0, 1)">).size()); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">hash</span> jedis.hset("hash1","userName","lisi"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(jedis.hget(</span>"hash1","userName"<span style="color: rgba(0, 0, 0, 1)">)); Map</span><String,String> map = <span style="color: rgba(0, 0, 255, 1)">new</span> HashMap<String,String><span style="color: rgba(0, 0, 0, 1)">(); map.put(</span>"telphone","13811814763"<span style="color: rgba(0, 0, 0, 1)">); map.put(</span>"address","atguigu"<span style="color: rgba(0, 0, 0, 1)">); map.put(</span>"email","abc@163.com"<span style="color: rgba(0, 0, 0, 1)">); jedis.hmset(</span>"hash2"<span style="color: rgba(0, 0, 0, 1)">,map); List</span><String> result = jedis.hmget("hash2", "telphone","email"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (String element : result) { System.out.println(element); } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">zset</span> jedis.zadd("zset01",60d,"v1"<span style="color: rgba(0, 0, 0, 1)">); jedis.zadd(</span>"zset01",70d,"v2"<span style="color: rgba(0, 0, 0, 1)">); jedis.zadd(</span>"zset01",80d,"v3"<span style="color: rgba(0, 0, 0, 1)">); jedis.zadd(</span>"zset01",90d,"v4"<span style="color: rgba(0, 0, 0, 1)">); Set</span><String> s1 = jedis.zrange("zset01",0,-1<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Iterator iterator =<span style="color: rgba(0, 0, 0, 1)"> s1.iterator(); iterator.hasNext();) { String string </span>=<span style="color: rgba(0, 0, 0, 1)"> (String) iterator.next(); System.out.println(string); }
}
}
3. 事务提交
【1】日常
package com.atguigu.redis.test;import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;public class Test03
{
public static void main(String[] args)
{
Jedis jedis = new Jedis("127.0.0.1",6379);</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">监控key,如果该动了事务就被放弃</span> <span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">3 jedis.watch("serialNum"); jedis.set("serialNum","s#####################"); jedis.unwatch();</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)"> Transaction transaction </span>= jedis.multi();<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">被当作一个命令进行执行</span> Response<String> response = transaction.get("serialNum"<span style="color: rgba(0, 0, 0, 1)">); transaction.set(</span>"serialNum","s002"<span style="color: rgba(0, 0, 0, 1)">); response </span>= transaction.get("serialNum"<span style="color: rgba(0, 0, 0, 1)">); transaction.lpush(</span>"list3","a"<span style="color: rgba(0, 0, 0, 1)">); transaction.lpush(</span>"list3","b"<span style="color: rgba(0, 0, 0, 1)">); transaction.lpush(</span>"list3","c"<span style="color: rgba(0, 0, 0, 1)">); transaction.exec(); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">2 transaction.discard();</span> System.out.println("serialNum***********"+<span style="color: rgba(0, 0, 0, 1)">response.get());
}
}
【2】加锁
public class TestTransaction {public boolean transMethod() {
Jedis jedis = new Jedis("127.0.0.1", 6379);
int balance;// 可用余额
int debt;// 欠额
int amtToSubtract = 10;// 实刷额度
jedis.watch("balance");
//jedis.set("balance","5");//此句不该出现,讲课方便。模拟其他程序已经修改了该条目
balance = Integer.parseInt(jedis.get("balance"));
if (balance < amtToSubtract) {
jedis.unwatch();
System.out.println("modify");
return false;
} else {
System.out.println("***********transaction");
Transaction transaction = jedis.multi();
transaction.decrBy("balance", amtToSubtract);
transaction.incrBy("debt", amtToSubtract);
transaction.exec();
balance = Integer.parseInt(jedis.get("balance"));
debt = Integer.parseInt(jedis.get("debt"));System.out.println(</span>"*******" +<span style="color: rgba(0, 0, 0, 1)"> balance); System.out.println(</span>"*******" +<span style="color: rgba(0, 0, 0, 1)"> debt); </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">; }
}
/**
- 通俗点讲,watch 命令就是标记一个键,如果标记了一个键, 在提交事务前如果该键被别人修改过,那事务就会失败,这种情况通常可以在程序中
- 重新再尝试一次。
- 首先标记了键 balance,然后检查余额是否足够,不足就取消标记,并不做扣减; 足够的话,就启动事务进行更新操作,
- 如果在此期间键 balance 被其它人修改, 那在提交事务(执行 exec)时就会报错, 程序中通常可以捕获这类错误再重新执行一次,直到成功。
*/
public static void main(String[] args) {
TestTransaction test = new TestTransaction();
boolean retValue = test.transMethod();
System.out.println("main retValue-------:" + retValue);
}
}
4. 主从复制
6379,6380 启动,先各自先独立
主写
从读
五、JedisPool
1. 获取 Jedis 实例需要从 JedisPool 中获取
2. 用完 Jedis 实例需要返还给 JedisPool
3. 如果 Jedis 在使用过程中出错,则也需要还给 JedisPool
4. 案例见代码
5. 配置总结 all
JedisPool 的配置参数大部分是由 JedisPoolConfig 的对应项来赋值的。
maxActive:控制一个 pool 可分配多少个 jedis 实例,通过 pool.getResource() 来获取;如果赋值为 -1,则表示不限制;如果 pool 已经分配了 maxActive 个 jedis 实例,则此时 pool 的状态为 exhausted。
maxIdle:控制一个 pool 最多有多少个状态为 idle(空闲) 的 jedis 实例;
whenExhaustedAction:表示当 pool 中的 jedis 实例都被 allocated 完时,pool 要采取的操作;默认有三种。
WHEN_EXHAUSTED_FAIL --> 表示无 jedis 实例时,直接抛出 NoSuchElementException;
WHEN_EXHAUSTED_BLOCK --> 则表示阻塞住,或者达到 maxWait 时抛出 JedisConnectionException;
WHEN_EXHAUSTED_GROW --> 则表示新建一个 jedis 实例,也就说设置的 maxActive 无用;
maxWait:表示当 borrow 一个 jedis 实例时,最大的等待时间,如果超过等待时间,则直接抛 JedisConnectionException;
testOnBorrow:获得一个 jedis 实例的时候是否检查连接可用性(ping());如果为 true,则得到的 jedis 实例均是可用的;
testOnReturn:return 一个 jedis 实例给 pool 时,是否检查连接可用性(ping());
testWhileIdle:如果为 true,表示有一个 idle object evitor 线程对 idle object 进行扫描,如果 validate 失败,此 object 会被从 pool 中 drop 掉;这一项只有在 timeBetweenEvictionRunsMillis 大于 0 时才有意义;
timeBetweenEvictionRunsMillis:表示 idle object evitor 两次扫描之间要 sleep 的毫秒数;
numTestsPerEvictionRun:表示 idle object evitor 每次扫描的最多的对象数;
minEvictableIdleTimeMillis:表示一个对象至少停留在 idle 状态的最短时间,然后才能被 idle object evitor 扫描并驱逐;这一项只有在 timeBetweenEvictionRunsMillis 大于 0 时才有意义;
softMinEvictableIdleTimeMillis:在 minEvictableIdleTimeMillis 基础上,加入了至少 minIdle 个对象已经在 pool 里面了。如果为 -1,evicted 不会根据 idle time 驱逐任何对象。如果 minEvictableIdleTimeMillis>0,则此项设置无意义,且只有在 timeBetweenEvictionRunsMillis 大于 0 时才有意义;
lifo:borrowObject 返回对象时,是采用 DEFAULT_LIFO(last in first out,即类似 cache 的最频繁使用队列),如果为 False,则表示 FIFO 队列;
==================================================================================================================
其中 JedisPoolConfig 对一些参数的默认设置如下:
testWhileIdle=true
minEvictableIdleTimeMills=60000
timeBetweenEvictionRunsMillis=30000
numTestsPerEvictionRun=-1
源码:
package com.atguigu.redis.test;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtil
{
private static volatile JedisPool jedisPool = null;</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> JedisPoolUtil(){} </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> JedisPool getJedisPoolInstance() { </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">null</span> ==<span style="color: rgba(0, 0, 0, 1)"> jedisPool) { </span><span style="color: rgba(0, 0, 255, 1)">synchronized</span> (JedisPoolUtil.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">) { </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">null</span> ==<span style="color: rgba(0, 0, 0, 1)"> jedisPool) { JedisPoolConfig poolConfig </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JedisPoolConfig(); poolConfig.setMaxActive(</span>1000<span style="color: rgba(0, 0, 0, 1)">); poolConfig.setMaxIdle(</span>32<span style="color: rgba(0, 0, 0, 1)">); poolConfig.setMaxWait(</span>100*1000<span style="color: rgba(0, 0, 0, 1)">); poolConfig.setTestOnBorrow(</span><span style="color: rgba(0, 0, 255, 1)">true</span><span style="color: rgba(0, 0, 0, 1)">); jedisPool </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> JedisPool(poolConfig,"127.0.0.1",6379<span style="color: rgba(0, 0, 0, 1)">); } } } </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> jedisPool; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> release(JedisPool jedisPool,Jedis jedis) { </span><span style="color: rgba(0, 0, 255, 1)">if</span>(<span style="color: rgba(0, 0, 255, 1)">null</span> !=<span style="color: rgba(0, 0, 0, 1)"> jedis) { jedisPool.returnResourceObject(jedis); } }
}
package com.atguigu.redis.test;import redis.clients.jedis.Jedis;
public class TestMS {
public static void main(String[] args) {
Jedis jedis_M = new Jedis("127.0.0.1",6379);
Jedis jedis_S = new Jedis("127.0.0.1",6380);jedis_S.slaveof(</span>"127.0.0.1",6379<span style="color: rgba(0, 0, 0, 1)">); jedis_M.set(</span>"class","1122V2"<span style="color: rgba(0, 0, 0, 1)">); String result </span>= jedis_S.get("class"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(result); }
}
package com.atguigu.redis.test;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;public class TestPool {
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) { JedisPool jedisPool </span>=<span style="color: rgba(0, 0, 0, 1)"> JedisPoolUtil.getJedisPoolInstance(); JedisPool jedisPool2 </span>=<span style="color: rgba(0, 0, 0, 1)"> JedisPoolUtil.getJedisPoolInstance(); System.out.println(jedisPool </span>==<span style="color: rgba(0, 0, 0, 1)"> jedisPool2); Jedis jedis </span>= <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">; </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> { jedis </span>=<span style="color: rgba(0, 0, 0, 1)"> jedisPool.getResource(); jedis.set(</span>"aa","bb"<span style="color: rgba(0, 0, 0, 1)">); } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) { e.printStackTrace(); }</span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">{ JedisPoolUtil.release(jedisPool, jedis); } }
}
到此,redis 学习告一段落,通过学习对 redis 的功能和使用有了一定程度的掌握,基本使用应该没有问题了。后续将学习消息中间件 kafka