jedis 事务
Transaction transaction = jedis.multi();
transaction.set("k4","v4");
transaction.set("k4","v4");
transaction.exec();
transaction.discard();
jedis锁-watch()标记一个key
watch命令标记一个键,在提交事务前如果键被别人修改过,那么事务就会失败,这种情况通常可以在程序中重新再尝试一次。
模拟银行转账的过程
127.0.0.1:6379>set balance 100
127.0.0.1:6379>set debt 0
public boolean transaction() throws InterrupttedException{
Jedis jedis = new Jedis("127.0.0.1",6379);
int balance;
int debt;
int amtToSubtract = 10;//实刷额度
jedis.watch("balance");
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",amtToSubstract);
transaction.incrBy("balance",amtToSubstract);
transaction.exec();
return true;
}
}
模拟在事务执行的时候balance的值发生改变的情况:
Thread.sleep(7000); // 线程休息7s,在redis的客户端修改balance的值。
jedisPool
多个connection连接:
为什么要有池:java的new gc需要消耗很多内存
线程的获得由线程池
数据库的连接有数据库连接池
JedisPool jedis = new JedisPool(poolConfig,”127.0.0.1”,6379);
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxActive(1000);
poolConfig.setMaxIdle(32);//jedis不能变满
poolConfig.setMaxWait(100*1000);
poolConfig.setTestOnBorrow(true);
使用单例模式
public class JedisPoolUtil{
private static volatile JedisPool jedisPool = null;
private JedisPoolUtil(){}
public static JedisPool getJedisPoolInstance(){
if(null == jedisPool){
synchronized(JedisPoolUtil.class){
if(null == jedisPool){
JedisPool jedis = new JedisPool(poolConfig,"127.0.0.1",6379);
}
}
}
}
public static void release(JedisPool jedisPool,Jedis jedis){
if(jedis != null){
jedisPool.returnResourceObject(jedis)
}
}
}
jedisPool = JedisPoolUtil.getJedisPoolInstance();
jedis = jedisPool.getResource()
//在finally里面执行释放资源