1. 新建一个名为JedisTransaction的Java项目, 拷入相关jar包, 并添加到build path
2. 编辑JedisTransaction.java
package com.redis.transaction;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* Jedis事物
*/
public class JedisTransaction {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
weChatPay();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
alipay();
}
}).start();
}
public static void alipay() {
try {
Jedis jedis = new Jedis("192.168.25.138", 6379);
jedis.auth("lyw123456");
System.out.println("alipay start...");
// 监听key
jedis.watch("lock");
// 开始事物
Transaction transaction = jedis.multi();
transaction.set("lock", "click game pay");
transaction.set("lock", "create game pay order");
transaction.set("lock", "show pay ui");
transaction.set("lock", "choose alipay");
transaction.set("lock", "alipay create order");
Thread.sleep(2000);
transaction.set("lock", "pay money");
transaction.set("lock", "ali receive money");
transaction.set("lock", "ali send pay call back to game server");
transaction.set("lock", "game server receive ali pay call back");
transaction.set("lock", "game send add coin commond to game client");
transaction.set("lock", "game client add coin");
// 提交事物
List<Object> list = transaction.exec();
for (Object object : list) {
System.out.println("alipay: " + object);
}
System.out.println("alipay end...");
jedis.close();
} catch (Exception e) {
System.out.println("alipay exception: " + e.getMessage());
e.printStackTrace();
}
}
public static void weChatPay() {
try {
Jedis jedis = new Jedis("192.168.25.138", 6379);
jedis.auth("lyw123456");
System.out.println("wechatpay start...");
// 监听key
jedis.watch("lock");
// 开始事物
Transaction transaction = jedis.multi();
transaction.set("lock", "click game pay");
transaction.set("lock", "create game pay order");
Thread.sleep(3000);
transaction.set("lock", "show pay ui");
transaction.set("lock", "choose wechatpay");
transaction.set("lock", "wechatpay create order");
transaction.set("lock", "pay money");
transaction.set("lock", "wechat receive money");
transaction.set("lock", "wechat send pay call back to game server");
transaction.set("lock", "game server receive wechat pay call back");
transaction.set("lock", "game send add coin commond to game client");
transaction.set("lock", "game client add coin");
// 提交事物
List<Object> list = transaction.exec();
for (Object object : list) {
System.out.println("wechatpay: " + object);
}
System.out.println("wechatpay end...");
jedis.close();
} catch (Exception e) {
System.out.println("wechatpay exception: " + e.getMessage());
e.printStackTrace();
}
}
}
3. 运行结果