Alpakka為集成各種用例,提供了各種Akka Stream連接器、集成模式和數(shù)據(jù)轉(zhuǎn)換。
例如Spring Web
Spring 5.0引入了Reactive Streams的兼容性。
由于采用了Reactive Streams,多個(gè)庫(kù)現(xiàn)在可以互操作,因?yàn)樗羞@些庫(kù)都實(shí)現(xiàn)了相同的接口。按照設(shè)計(jì),Akka Stream隱藏了終端用戶的原始響應(yīng)流類型,因?yàn)樗试S從響應(yīng)流分離這些類型,并允許無(wú)縫遷移到 java.util.concurrent.Flow(在Java9引入)。
此 Alpakka 模塊使您可以直接返回 Spring Web 終結(jié)點(diǎn)中的源。
在Spring Web(或Spring Boot)中使用Akka Streams是非常簡(jiǎn)單的,因?yàn)锳lpakka提供了對(duì)框架的自動(dòng)配置,這意味著Spring已經(jīng)知道了Sources和Sinks等。
所有你需要做的就是引入上面的依賴(akka-stream-alpakka-spring-web),像往常一樣啟動(dòng)你的應(yīng)用程序:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
你可以直接在HTTP端點(diǎn)返回Akka Streams:
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.Materializer;
import akka.stream.javadsl.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@RequestMapping("/")
public Source<String, NotUsed> index() {
return
Source.repeat("Hello world!")
.intersperse("\n")
.take(10);
}
}
javadsl 和scaladsl Akka Stream 類型均支持。
所提供的配置
自動(dòng)啟用的配置如下:
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
@Configuration
@ConditionalOnClass(akka.stream.javadsl.Source.class)
public class SpringWebAkkaStreamsConfiguration {
private final ActorSystem system;
private final ActorMaterializer mat;
@Autowired
public SpringWebAkkaStreamsConfiguration(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
final ReactiveAdapterRegistry registry = requestMappingHandlerAdapter.getReactiveAdapterRegistry();
system = ActorSystem.create("SpringWebAkkaStreamsSystem");
mat = ActorMaterializer.create(system);
new AkkaStreamsRegistrar(mat).registerAdapters(registry);
}
@Bean
@ConditionalOnMissingBean(ActorSystem.class)
public ActorSystem getActorSystem() {
return system;
}
@Bean
@ConditionalOnMissingBean(Materializer.class)
public ActorMaterializer getMaterializer() {
return mat;
}
}
如果你想手動(dòng)配置稍有不同。
雖然這里介紹的集成有效,但并不是將Akka與服務(wù)HTTP應(yīng)用程序結(jié)合使用的最佳方式。建議使用Akka HTTP。