import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TranRedis {
private Jedis js=new Jedis("localhost",6379);
@Test
public void init(){
js.select(1);//选择o号库
js.set("balance", "1000");//设置余额
js.set("debt", "0");//设置欠费;
System.out.println("数据添加成功");
System.out.println("balance:"+js.get("balance"));
System.out.println("debt:"+js.get("debt"));
}
/*
* 测试正常状态下
*/
@Test
public void tran1() throws InterruptedException{
js.select(1);//选择o号库
int amtToSubtract=10;//消费
js.watch("balance");//监视
int balance=Integer.parseInt(js.get("balance"));//余额
if(balance>amtToSubtract){
Transaction transaction=js.multi();//开启事物
transaction.decrBy("balance", amtToSubtract);//余额减少
transaction.incrBy("debt", amtToSubtract);//欠费增加
transaction.exec();//执行事物
System.out.println("此次交易成功");
System.out.println("balance:"+js.get("balance"));
System.out.println("debt:"+js.get("debt"));
}else{
js.unwatch();//不监视
System.out.println("网络延时,此次交易失败!");
System.out.println("数据被修改");
System.out.println("balance:"+js.get("balance"));
System.out.println("debt:"+js.get("balance"));
}
}
/*
* 测试非正常状态下
*/
@Test
public void tran2() throws InterruptedException{
js.select(1);//选择o号库
int amtToSubtract=10;//消费
js.watch("balance");//监视
for (int i = 1; i < 7; i++) {
System.out.println("第"+i+"秒");
Thread.sleep(1000);
if(i==5){
System.out.println("在第5秒中,该余额数据已被修改");
js.set("balance", "5");
}
}
int balance=Integer.parseInt(js.get("balance"));//余额
if(balance>amtToSubtract){
Transaction transaction=js.multi();//开启事物
transaction.decrBy("balance", amtToSubtract);//余额减少
transaction.incrBy("debt", amtToSubtract);//欠费增加
transaction.exec();
}else{
js.unwatch();
System.out.println("网络延时,此次交易失败!");
System.out.println("数据被修改");
System.out.println("balance:"+js.get("balance"));
System.out.println("debt:"+js.get("debt"));
}
}
}
1.执行init方法
2.执行tran1方法
3.执行tran2方法