前言:取消订单有很多种实现方式,通过redis
来实时监测订单的状态变化,并及时处理相关事件,比如取消订单、重新上架商品等。通过这种方式,系统可以实现订单的自动管理,提高了系统的可靠性和效率。
前置准备
Redis工具类用来实现放入订单 过期通知
1 2 3 4
| public static void zadd(String key, double score, String member) { RedisPool.getWriteJedis().zadd(key, score, member); }
|
下单操作
1 2 3 4 5 6 7 8 9
| public void addOrder(Model model) {
Calendar cal1 = Calendar.getInstance(); cal1.add(Calendar.HOUR, 2); int timeStamp = (int) (cal1.getTimeInMillis() / 1000); CacheTool.zadd("addOrder", timeStamp, String.valueOf(order.getId())); }
|
取消订单
它首先获取一个用于读取数据的 Jedis 实例
,然后进入一个无限循环。在每次循环中,它会遍历两个集合,分别检查是否有成员已经到期。如果某个成员的时间戳早于当前时间,它会将该成员从有序集合中移除,并执行相应的处理逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.Tuple;
import java.util.Arrays; import java.util.Calendar; import java.util.HashSet; import java.util.Set;
@Component public class MyThread implements InitializingBean {
@Override public void afterPropertiesSet() { Thread thread = new Thread(() -> { Jedis jedis = RedisPool.getReadJedis(); while (true) { Set<String> keys = new HashSet<>(Arrays.asList("addOrder", "orderPay")); for (String key : keys) { Set<Tuple> items = jedis.zrangeWithScores(key, 0, 1); if (items == null || items.isEmpty()) { continue; } Tuple item = items.iterator().next(); int score = (int) item.getScore(); Calendar cal = Calendar.getInstance(); int nowSecond = (int) (cal.getTimeInMillis() / 1000); if (nowSecond < score) { continue; } Long num = jedis.zrem(key, item.getElement()); if (num == null || num <= 0) { continue; } if ("addOrder".equals(key)) { handleAddOrder(item.getElement()); } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }
}); thread.start(); }
private void handleAddOrder(String id) { } }
|