有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java spring webflux:如何从同步调用发布事件以进行异步处理?

我有一个同步调用的方法。通过这个方法,我想发布另一个将被异步处理的事件。例如:

正在使用参数调用同步方法M,需要将此参数发送到其他服务器X。M应尽快返回,但X可能会关闭。如果X关闭,异步处理应该在几秒钟后重试几次

所以我有一个处理单个均衡器/参数的代码:

 return webClient
                .post()
                .uri(...)
                .syncBody(...)
                .retrieve().bodyToMono(...)
                .retryWhen {...}
                .subscribeOn(Schedulers.boundedElastic())

但如何从同步调用发布新的事件/参数


共 (1) 个答案

  1. # 1 楼答案

    spring提供的一个很好的开箱即用的解决方案叫做Spring Cloud Gateway,它正好满足了您的要求:

    这是一款无代码应用程序,您可以立即启动,并使用yaml配置配置所有路由,还可以通过配置轻松为每条路由应用所需的重试退避等:

    它提供了一个内置的重试网关过滤器工厂,可以提供所需的解决方案

    The Retry GatewayFilter factory supports the following parameters:
    
    retries: The number of retries that should be attempted.
    
    statuses: The HTTP status codes that should be retried, represented by using org.springframework.http.HttpStatus.
    
    methods: The HTTP methods that should be retried, represented by using org.springframework.http.HttpMethod.
    
    series: The series of status codes to be retried, represented by using org.springframework.http.HttpStatus.Series.
    
    exceptions: A list of thrown exceptions that should be retried.
    
    backoff: The configured exponential backoff for the retries. Retries are performed after a backoff interval of firstBackoff * (factor ^ n), where n is the iteration. If maxBackoff is configured, the maximum backoff applied is limited to maxBackoff. If basedOnPreviousValue is true, the backoff is calculated byusing prevBackoff * factor.
    
    The following defaults are configured for Retry filter, if enabled:
    
    retries: Three times
    
    series: 5XX series
    
    methods: GET method
    
    exceptions: IOException and TimeoutException
    
    backoff: disabled
    

    示例Yaml配置再次无需代码:):

    spring:
      cloud:
        gateway:
          routes:
          - id: retry_test
            uri: http://localhost:8080/flakey
            predicates:
            - Host=*.retry.com
            filters:
            - name: Retry
              args:
                retries: 3
                statuses: BAD_GATEWAY
                methods: GET,POST
                backoff:
                  firstBackoff: 10ms
                  maxBackoff: 50ms
                  factor: 2
                  basedOnPreviousValue: false