适用于订单超时取消,代码注释已经很详细了,不多叙述
public class yanshirenwu {
private static final String ADDR = "127.0.0.1";
private static final int PORT = 6379;
private static JedisPool jedisPool = new JedisPool(ADDR, PORT);
public static Jedis getJedis() {
return jedisPool.getResource();
}
//生产者,生成5个订单放进去
public void productionDelayMessage(){
for(int i=0;i<5;i++){
//随机延迟
Calendar cal1 = Calendar.getInstance();
int yanshi=(int)(1+Math.random()*(5-1+1));
cal1.add(Calendar.SECOND,yanshi );
Date data=new Date();
int second3later = (int) (cal1.getTimeInMillis() / 1000);
yanshirenwu.getJedis().zadd("OrderId", second3later,"OID0000001"+i);
System.out.println(data.toString()+":redis生成了一个延时"+yanshi+"秒的订单任务:订单ID为"+"OID0000001"+i);
}
}
//消费者,取订单
public void consumerDelayMessage(){
Jedis jedis = yanshirenwu.getJedis();
while(true){
//获取分值最小的一个订单号(分值为时间戳,时间最小的订单,可以根据业务需要取多个)
Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);
if(items == null || items.isEmpty()){
System.out.println("当前没有等待的任务");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
}
//获取分钟
int score = (int) ((Tuple)items.toArray()[0]).getScore();
Calendar cal = Calendar.getInstance();
int nowSecond = (int) (cal.getTimeInMillis() / 1000);
//过期则删除订单(此处写业务逻辑)
if(nowSecond >= score){
String orderId = ((Tuple)items.toArray()[0]).getElement();
//同一订单可能被多个线程拿到,成功删除才执行取消订单
if(jedis.zrem("OrderId", orderId)>0){
Date data1=new Date();
System.out.println(data1.toString() +":redis消费了一个任务:消费的订单OrderId为"+orderId);
}else {
System.out.println("已被其他线程消费");
}
}
}
}
public static void main(String[] args) {
yanshirenwu appTest =new yanshirenwu();
int threadNum=10;
appTest.productionDelayMessage();
for(int i=0;i<threadNum;i++){
new Thread(new DelayMessage(appTest)).start();
}
}
}