第2章——反应式宣言概览

这一章详细地介绍了《反应式宣言》:原文文字简练且内容紧凑,我们将在这里加以展开并进行深入地讨论。有关该宣言相关理论的更多背景知识,请参阅本书第二部分。

2.1 对用户作出反应

代码清单 2-1 图片服务中简单 Controller 的一段代码

public interface Images {
  Image get(String key);

  void add(String key, Image image);
}

private Images cache;
private Images database;

public Image retrieveImages(String key) {
  Image result = cache.get(key);
  if (result != null) {
    return result;
  } else {
    result = database.get(key);
    if (result != null) {
      cache.add(key, result);
      return result;
    } else {
      return FALLBACK;
    }
  }
}

2.2 利用并行性

SimpleFunction.scala

val result = f(42)

SequentialExecution.java

final ReplyA a = computeA();
final ReplyB b = computeB();
final ReplyC c = computeC();

final Result r = aggregate(a, b, c);

ParallelExecutionWithJavaFuture.java

final Future<ReplyA> a = taskA();
final Future<ReplyB> b = taskB();
final Future<ReplyC> c = taskC();

final Result r = aggregate(a.get(), b.get(), c.get());

ParallelExecutionWithScalaFuture.scala

val fa: Future[ReplyA] = taskA()
val fb: Future[ReplyB] = taskB()
val fc: Future[ReplyC] = taskC()

val fr: Future[Result] =
  for (a <- fa; b <- fb; c <- fc)
    yield aggregate(a, b, c)

BlockingSocketRead.java

final Socket socket = new Socket("127.0.0.1", 8080);
socket.getOutputStream().write(requestMessageBytes);
final int bytesRead = socket.getInputStream().read(responseBuffer);

AskActorWithJava8.java

final CompletionStage<Response> future =
    ask(actorRef, request, timeout).thenApply(Response.class::cast);
future.thenAccept(AskActorWithJava8::processIt);

2.4 对失败作出反应

ExceptionHandler.scala

try {
  f(i)
} catch {
  case _: java.lang.ArithmeticException => Int.MaxValue
  case ex: java.lang.StackOverflowError => ???
  case ex: java.net.ConnectException    => ???
}