本文整理了Java中reactor.core.publisher.Mono.switchIfEmpty()
方法的一些代码示例,展示了Mono.switchIfEmpty()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mono.switchIfEmpty()
方法的具体详情如下:
包路径:reactor.core.publisher.Mono
类名称:Mono
方法名:switchIfEmpty
[英]Fallback to an alternative Mono if this mono is completed without data
[中]如果此单声道在没有数据的情况下完成,则返回到备用单声道
代码示例来源:origin: codecentric/spring-boot-admin
@Override
public Mono<Endpoints> detectEndpoints(Instance instance) {
Mono<Endpoints> result = Mono.empty();
for (EndpointDetectionStrategy delegate : delegates) {
result = result.switchIfEmpty(delegate.detectEndpoints(instance));
}
return result.switchIfEmpty(Mono.just(Endpoints.empty()));
}
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<HandlerFunction<ServerResponse>> route(ServerRequest request) {
return this.first.route(request)
.map(RouterFunctions::cast)
.switchIfEmpty(Mono.defer(() -> this.second.route(request).map(RouterFunctions::cast)));
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected Mono<Resource> resolveResourceInternal(@Nullable ServerWebExchange exchange,
String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return chain.resolveResource(exchange, requestPath, locations)
.switchIfEmpty(Mono.defer(() ->
resolveVersionedResource(exchange, requestPath, locations, chain)));
}
代码示例来源:origin: codecentric/spring-boot-admin
@Override
public Mono<Instance> compute(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) {
return this.find(id)
.flatMap(application -> remappingFunction.apply(id, application))
.switchIfEmpty(Mono.defer(() -> remappingFunction.apply(id, null)))
.flatMap(this::save)
.retryWhen(retryOnOptimisticLockException);
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected Mono<Resource> resolveResourceInternal(@Nullable ServerWebExchange exchange,
String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return chain.resolveResource(exchange, requestPath, locations)
.switchIfEmpty(Mono.defer(() -> {
String webJarsResourcePath = findWebJarResourcePath(requestPath);
if (webJarsResourcePath != null) {
return chain.resolveResource(exchange, webJarsResourcePath, locations);
}
else {
return Mono.empty();
}
}));
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<HandlerFunction<T>> route(ServerRequest request) {
return this.first.route(request)
.switchIfEmpty(Mono.defer(() -> this.second.route(request)));
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected Mono<String> resolveUrlPathInternal(String resourceUrlPath,
List<? extends Resource> locations, ResourceResolverChain chain) {
return chain.resolveUrlPath(resourceUrlPath, locations)
.switchIfEmpty(Mono.defer(() -> {
String webJarResourcePath = findWebJarResourcePath(resourceUrlPath);
if (webJarResourcePath != null) {
return chain.resolveUrlPath(webJarResourcePath, locations);
}
else {
return Mono.empty();
}
}));
}
代码示例来源:origin: spring-projects/spring-framework
private <T> Mono<ResponseEntity<T>> toEntityInternal(Mono<T> bodyMono) {
HttpHeaders headers = headers().asHttpHeaders();
int status = rawStatusCode();
return bodyMono
.map(body -> createEntity(body, headers, status))
.switchIfEmpty(Mono.defer(
() -> Mono.just(createEntity(headers, status))));
}
代码示例来源:origin: spring-projects/spring-framework
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, String>> initFormData(ServerHttpRequest request,
List<HttpMessageReader<?>> readers) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, String>>) readers.stream()
.filter(reader -> reader.canRead(FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No form data HttpMessageReader.")))
.readMono(FORM_DATA_TYPE, request, Hints.none())
.switchIfEmpty(EMPTY_FORM_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_FORM_DATA;
}
代码示例来源:origin: spring-projects/spring-framework
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
List<HttpMessageReader<?>> readers) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, Part>>) readers.stream()
.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
.readMono(MULTIPART_DATA_TYPE, request, Hints.none())
.switchIfEmpty(EMPTY_MULTIPART_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_MULTIPART_DATA;
}
@Override
代码示例来源:origin: codecentric/spring-boot-admin
public static ExchangeFilterFunction setInstance(Mono<Instance> instance) {
return (request, next) -> instance.map(i -> ClientRequest.from(request)
.attribute(ATTRIBUTE_INSTANCE, i)
.build())
.switchIfEmpty(request.url().isAbsolute() ? Mono.just(request) : Mono.error(
new ResolveInstanceException("Could not resolve Instance")))
.flatMap(next::exchange);
}
代码示例来源:origin: spring-projects/spring-framework
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, String>> initFormData(ServerHttpRequest request,
ServerCodecConfigurer configurer, String logPrefix) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, String>>) configurer.getReaders().stream()
.filter(reader -> reader.canRead(FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No form data HttpMessageReader.")))
.readMono(FORM_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
.switchIfEmpty(EMPTY_FORM_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_FORM_DATA;
}
代码示例来源:origin: spring-projects/spring-framework
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
ServerCodecConfigurer configurer, String logPrefix) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, Part>>) configurer.getReaders().stream()
.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
.readMono(MULTIPART_DATA_TYPE, request, Hints.from(Hints.LOG_PREFIX_HINT, logPrefix))
.switchIfEmpty(EMPTY_MULTIPART_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_MULTIPART_DATA;
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
if (this.handlerMappings == null) {
return createNotFoundError();
}
return Flux.fromIterable(this.handlerMappings)
.concatMap(mapping -> mapping.getHandler(exchange))
.next()
.switchIfEmpty(createNotFoundError())
.flatMap(handler -> invokeHandler(exchange, handler))
.flatMap(result -> handleResult(exchange, result));
}
代码示例来源:origin: codecentric/spring-boot-admin
protected Mono<ClientResponse> forward(String instanceId,
URI uri,
HttpMethod method,
HttpHeaders headers,
Supplier<BodyInserter<?, ? super ClientHttpRequest>> bodyInserter) {
log.trace("Proxy-Request for instance {} with URL '{}'", instanceId, uri);
return registry.getInstance(InstanceId.of(instanceId))
.flatMap(instance -> forward(instance, uri, method, headers, bodyInserter))
.switchIfEmpty(Mono.fromSupplier(() -> ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE, strategies).build()));
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
MediaType contentType = exchange.getResponse().getHeaders().getContentType();
Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();
return Flux.fromStream(viewResolverStream)
.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
.next()
.switchIfEmpty(Mono.error(() ->
new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
.flatMap(view -> {
List<MediaType> mediaTypes = view.getSupportedMediaTypes();
return view.render(model(),
contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
exchange);
});
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<ClientResponse> exchange() {
ClientRequest request = (this.inserter != null ?
initRequestBuilder().body(this.inserter).build() :
initRequestBuilder().build());
return exchangeFunction.exchange(request).switchIfEmpty(NO_HTTP_CLIENT_RESPONSE_ERROR);
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<Object> resolveArgument(
MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
MethodParameter nestedParameter = parameter.nestedIfOptional();
Object resolvedName = resolveStringValue(namedValueInfo.name);
if (resolvedName == null) {
return Mono.error(new IllegalArgumentException(
"Specified name must not resolve to null: [" + namedValueInfo.name + "]"));
}
Model model = bindingContext.getModel();
return resolveName(resolvedName.toString(), nestedParameter, exchange)
.flatMap(arg -> {
if ("".equals(arg) && namedValueInfo.defaultValue != null) {
arg = resolveStringValue(namedValueInfo.defaultValue);
}
arg = applyConversion(arg, namedValueInfo, parameter, bindingContext, exchange);
handleResolvedValue(arg, namedValueInfo.name, parameter, model, exchange);
return Mono.justOrEmpty(arg);
})
.switchIfEmpty(getDefaultValue(
namedValueInfo, parameter, bindingContext, model, exchange));
}
代码示例来源:origin: spring-projects/spring-framework
@SuppressWarnings("unchecked")
@Override
public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
@Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) {
MediaType contentType = updateContentType(message, mediaType);
Flux<DataBuffer> body = this.encoder.encode(
inputStream, message.bufferFactory(), elementType, contentType, hints);
if (inputStream instanceof Mono) {
HttpHeaders headers = message.getHeaders();
return Mono.from(body)
.switchIfEmpty(Mono.defer(() -> {
headers.setContentLength(0);
return message.setComplete().then(Mono.empty());
}))
.flatMap(buffer -> {
headers.setContentLength(buffer.readableByteCount());
return message.writeWith(Mono.just(buffer));
});
}
return (isStreamingMediaType(contentType) ?
message.writeAndFlushWith(body.map(Flux::just)) : message.writeWith(body));
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public Mono<WebSession> getSession(ServerWebExchange exchange) {
return Mono.defer(() -> retrieveSession(exchange)
.switchIfEmpty(this.sessionStore.createWebSession())
.doOnNext(session -> exchange.getResponse().beforeCommit(() -> save(exchange, session))));
}
内容来源于网络,如有侵权,请联系作者删除!