如何为Java Project Reactor反应式
这是一个微不足道的Spring Boot 2.0.0-SNAPSHOT应用程序,它具有
使用Lombok的事件:
但是
Flux
API创建Angular 4客户端?以下示例有两个API:一个Mono
API和一个Flux
API。两者都可以使用curl
工作,但在Angular 4(4.1.2)中,只有Mono
API可以工作;有什么想法可以让Angular 4与Flux
API一起工作吗?这是一个微不足道的Spring Boot 2.0.0-SNAPSHOT应用程序,它具有
Mono
API和Flux
API:@SpringBootApplication
@RestController
public class ReactiveServiceApplication {
@CrossOrigin
@GetMapping("/events/{id}")
public Mono<Event> eventById(@PathVariable long id) {
return Mono.just(new Event(id, LocalDate.now()));
}
@CrossOrigin
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Event> events() {
Flux<Event> eventFlux = Flux.fromStream(
Stream.generate(
()->new Event(System.currentTimeMillis(), LocalDate.now()))
);
Flux<Long> durationFlux = Flux.interval(Duration.ofSeconds(1));
return Flux.zip(eventFlux, durationFlux).map(Tuple2::getT1);
}
public static void main(String[] args) {
SpringApplication.run(ReactiveServiceApplication.class);
}
}
使用Lombok的事件:
@Data
@AllArgsConstructor
public class Event {
private final long id;
private final LocalDate when;
}
这些响应式API与我期望的一样可以从curl中使用:
jan@linux-6o1s:~/src> curl -s http://localhost:8080/events/123
{"id":123,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}
对于非终止的Flux API同样适用:
jan@linux-6o1s:~/src> curl -s http://localhost:8080/events
data:{"id":1494887783347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}
data:{"id":1494887784348,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}
data:{"id":1494887785347,"when":{"year":2017,"month":"MAY","monthValue":5,"dayOfMonth":15,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":135,"leapYear":false,"chronology":{"calendarType":"iso8601","id":"ISO"}}}
...
使用RxJS的同样简单的Angular 4客户端:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
title = 'app works!';
event: Observable<Event>;
subscription: Subscription;
constructor(
private _http: Http
) {
}
ngOnInit() {
this.subscription = this._http
.get("http://localhost:8080/events/322")
.map(response => response.json())
.subscribe(
e => {
this.event = e;
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
对于 Mono
API,运作良好:
"http://localhost:8080/events/322"
但是
Flux
API:"http://localhost:8080/events"
不像 curl
,它从不触发事件处理程序。