SentinelConfig.java 1.2 KB
Newer Older
1
package com.youlai.gateway.config;
2 3 4 5

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.youlai.common.result.ResultCode;
6
import jakarta.annotation.PostConstruct;
7 8 9 10 11 12 13 14 15 16 17
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;


/**
 * 自定义网关流控异常
 *
 * @author haoxr
18
 * @since 2022/7/24
19 20
 */
@Configuration
21
public class SentinelConfig {
22 23 24

    @PostConstruct
    private void initBlockHandler() {
25 26 27 28 29 30 31 32 33
        GatewayCallbackManager.setBlockHandler(
                (exchange, t) ->
                        ServerResponse
                                .status(HttpStatus.TOO_MANY_REQUESTS)
                                .contentType(MediaType.APPLICATION_JSON)
                                .body(
                                        BodyInserters.fromValue(ResultCode.FLOW_LIMITING.toString())
                                )
        );
34 35
    }
}