一、回调函数接口
public interface CallBack {
void back(boolean flag);
}
二、调用方
public class Producer {
private MessageQueue messageQueue;
public Producer(MessageQueue messageQueue) {
this.messageQueue = messageQueue;
}
private ThreadLocal<Integer> retryCount = ThreadLocal.withInitial(() -> 1);
public void produceSyn(String message) {
try {
messageQueue.receiveMessage(message, new CallBack() {
@Override
public void back(boolean flag) {
if (flag) {
System.out.println("下单成功\n");
} else {
Integer current = retryCount.get();
System.out.println("下单失败,开始第" + current + "轮重试");
if (current < 3) {
retryCount.set(current + 1);
produceSyn(message);
} else {
System.out.println("重试之后依旧失败");
}
}
}
});
} finally {
retryCount.remove();
}
}
public void produceAsync(String message) {
new Thread(() -> {
messageQueue.receiveMessage(message, new CallBack() {
@Override
public void back(boolean flag) {
if (flag) {
System.out.println("下单成功");
} else {
System.out.println("下单失败");
}
}
});
}, "async-thread").start();
System.out.println("不管成功与否,干我自己的业务逻辑");
}
}
三、被调用方
public interface MessageQueue {
void receiveMessage(String message, CallBack callback);
}
public class OrderMessageQueue implements MessageQueue {
@Override
public void receiveMessage(String message, CallBack callback) {
System.out.println("Queue接收到的消息:" + message + "正在处理中...");
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Random random = new Random();
int randomNumber = random.nextInt(10);
if (randomNumber <= 5) {
callback.back(true);
} else {
callback.back(false);
}
}
}
四、测试类
public class Test {
public static void main(String[] args) {
Producer producer = new Producer(new OrderMessageQueue());
producer.produceSyn("Jack下单了!!");
}
}
结果展示
Queue接收到的消息:Jack下单了!!正在处理中...
下单失败,开始第1轮重试
Queue接收到的消息:Jack下单了!!正在处理中...
下单成功