Guarded Suspension 设计模式大体概念就是当服务请求过多时,先排起队,后慢慢进行处理。核心思想在于缓冲服务。当我们服务端处理客户端的请求过多时,超出了我们服务的及时处理能力范围,但是又不能放弃任何一个请求,此时,这种设计模式就应运而生,先让客户端的请求进行排队,后由服务端程序一个一个处理。这样就可以做到两不耽误。
代码演示之前先看一下各类所起到的作用:
角色 | 作用 |
---|---|
Request | 任务、请求 |
RequestQueue | 任务队列、请求队列 |
ClientThread | 客户端进程 |
ServerThread | 服务端进程 |
下面我们通过代码来演示这个场景:
//任务、请求
@Data
public class Request {
final private String value;
public Request(String value) {
this.value = value;
}
}
//任务队列、请求队列
public class RequestQueue {
private final LinkedList<Request> queue = new LinkedList<>();
public Request getRequest() {
synchronized (queue) {
while (queue.size() <= 0) {
try {
queue.wait();
} catch (InterruptedException e) {
return null;
}
}
}
return queue.removeFirst();
}
public void putRequest(Request request) {
synchronized (queue) {
queue.addLast(request);
//放完之后通知其他人
queue.notifyAll();
}
}
}
//客户端
public class ClientThread extends Thread {
private final RequestQueue queue;
private final Random random;
private final String sendValue;
public ClientThread(RequestQueue queue, String sendValue) {
this.queue = queue;
this.sendValue = sendValue;
random = new Random(System.currentTimeMillis());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(" Client -->Request --> Server " + sendValue + i);
queue.putRequest(new Request(sendValue + i));
try {
Thread.sleep(random.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//服务端
public class ServerThread extends Thread {
private final RequestQueue queue;
private final Random random;
private Boolean close = false;
public ServerThread(RequestQueue queue) {
this.queue = queue;
random = new Random(System.currentTimeMillis());
}
@Override
public void run() {
while (!close) {
Request request = queue.getRequest();
if (null == request) {
System.out.println(" Receive the empty request ");
continue;
}
System.out.println(" Server -->" + request.getValue());
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
return;
}
}
}
public void close() {
this.close = true;
//为true的时候可能在wait,那么状态flag就有可能获取不到、所以给他打断一下、然后返回null
this.interrupt();
}
}
//测试一下
public class SuspensionClient {
public static void main(String[] args) throws InterruptedException {
final RequestQueue queue = new RequestQueue();
new ClientThread(queue, "Orange").start();
ServerThread serverThread = new ServerThread(queue);
serverThread.start();
Thread.sleep(10000);
serverThread.close();
}
}