91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot與Spring Cloud Gateway的限流與熔斷策略

發布時間:2024-11-15 16:36:26 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

Spring Boot和Spring Cloud Gateway都是基于Spring生態系統的流行框架,它們提供了豐富的功能來簡化微服務架構的開發。在微服務架構中,限流和熔斷是兩種重要的保護機制,用于防止系統過載和故障擴散。下面分別介紹Spring Boot和Spring Cloud Gateway中的限流和熔斷策略。

Spring Boot中的限流與熔斷策略

限流

Spring Boot提供了多種限流策略,可以通過以下幾種方式實現:

  1. 基于Guava RateLimiter: Spring Boot可以集成Guava庫中的RateLimiter來實現限流。首先,需要在pom.xml中添加Guava依賴:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>30.1-jre</version>
    </dependency>
    

    然后,在配置類中配置RateLimiter:

    import com.google.common.util.concurrent.RateLimiter;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class RateLimiterConfig {
    
        @Bean
        public RateLimiter rateLimiter() {
            return RateLimiter.create(1); // 每秒最多處理1個請求
        }
    }
    

    在需要限流的方法上使用@RateLimiter注解:

    import com.google.common.util.concurrent.RateLimiter;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MyController {
    
        @Autowired
        private RateLimiter rateLimiter;
    
        @GetMapping("/limited")
        public String limited() {
            if (rateLimiter.tryAcquire()) {
                return "Request accepted";
            } else {
                return "Request rejected";
            }
        }
    }
    
  2. 基于Redis的限流: 可以使用Spring Data Redis來實現基于Redis的限流。首先,需要在pom.xml中添加Redis依賴:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    

    然后,在配置類中配置Redis:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, String> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new StringRedisSerializer());
            return template;
        }
    }
    

    創建一個限流器:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class RedisRateLimiter {
    
        @Autowired
        private RedisTemplate<String, String> redisTemplate;
    
        public boolean tryAcquire(String key, int permits, long timeout, TimeUnit timeUnit) {
            String current = redisTemplate.opsForValue().get(key);
            if (current == null || Integer.parseInt(current) < permits) {
                redisTemplate.opsForValue().set(key, permits, timeout, timeUnit);
                return true;
            }
            return false;
        }
    }
    

    在需要限流的方法上使用@RedisRateLimiter注解:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class MyController {
    
        @Autowired
        private RedisRateLimiter redisRateLimiter;
    
        @GetMapping("/redis-limited")
        public String redisLimited() {
            if (redisRateLimiter.tryAcquire("myKey", 1, 10, TimeUnit.SECONDS)) {
                return "Request accepted";
            } else {
                return "Request rejected";
            }
        }
    }
    

熔斷

Spring Boot可以通過Hystrix來實現熔斷功能。首先,需要在pom.xml中添加Hystrix依賴:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

然后,在啟動類上添加@EnableCircuitBreaker注解:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableCircuitBreaker;

@SpringBootApplication
@EnableCircuitBreaker
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

在需要熔斷的方法上添加@HystrixCommand注解:

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public String myMethod() {
        // 實際的業務邏輯
        return "Success";
    }

    public String fallbackMethod() {
        return "Fallback response";
    }
}

Spring Cloud Gateway中的限流與熔斷策略

限流

Spring Cloud Gateway提供了多種限流策略,可以通過以下幾種方式實現:

  1. 基于Guava RateLimiter: 可以使用Spring Cloud Gateway的RateLimiter GatewayFilter Factory來實現限流。首先,需要在pom.xml中添加Guava依賴:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>30.1-jre</version>
    </dependency>
    

    然后,在配置類中配置RateLimiter:

    import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import reactor.core.publisher.Mono;
    
    @Configuration
    public class RateLimiterConfig {
    
        @Bean
        public KeyResolver userKeyResolver() {
            return new KeyResolver() {
                @Override
                public Mono<String> resolve(ServerWebExchange exchange) {
                    return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
                }
            };
        }
    }
    

    在路由配置中使用RateLimiter GatewayFilter Factory:

    spring:
      cloud:
        gateway:
          routes:
            - id: my_route
              uri: http://my-service-url
              filters:
                - name: RequestRateLimiter
                  args:
                    redis-rate-limiter.replenishRate: 10
                    redis-rate-limiter.burstCapacity: 20
                    key-resolver: "#{@userKeyResolver}"
    
  2. 基于Redis的限流: 可以使用Spring Cloud Gateway的RedisRateLimiter GatewayFilter Factory來實現基于Redis的限流。首先,需要在pom.xml中添加Spring Data Redis依賴:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    

    然后,在配置類中配置Redis:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, String> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new StringRedisSerializer());
            return template;
        }
    }
    

    在路由配置中使用RedisRateLimiter GatewayFilter Factory:

    spring:
      cloud:
        gateway:
          routes:
            - id: my_route
              uri: http://my-service-url
              filters:
                - name: RedisRateLimiter
                  args:
                    redis-rate-limiter.replenishRate: 10
                    redis-rate-limiter.burstCapacity: 20
    

熔斷

Spring Cloud Gateway可以通過Resilience4j來實現熔斷功能。首先,需要在pom.xml中添加Resilience4j依賴:

<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
</dependency>

然后,在配置類中配置Resilience4j:

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class Resilience4jConfig {

    @Bean
    public KeyResolver userKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
            }
        };
    }

    @Bean
    public CircuitBreakerRegistry circuitBreakerRegistry() {
        CircuitBreakerConfig config = CircuitBreakerConfig.custom()
                .failureRateThreshold(50)
                .waitDurationInOpenState(Duration.ofMillis(1000))
                .permittedNumberOfCallsInHalfOpenState(10)
                .build();
        return CircuitBreakerRegistry.of(config);
    }

    @Bean
    public CircuitBreaker circuitBreaker(CircuitBreakerRegistry registry) {
        return registry.circuitBreaker("myCircuitBreaker");
    }
}

在路由配置中使用CircuitBreaker GatewayFilter Factory:

spring:
  cloud:
    gateway:
      routes:
        - id: my_route
          uri: http://my-service-url
          filters:
            - name: CircuitBreaker
              args:
                name: myCircuitBreaker
                fallbackUri: forward:/fallback

通過以上配置,可以實現Spring Boot和Spring Cloud Gateway中的限流和熔斷策略。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

壤塘县| 诸城市| 渭南市| 宝清县| 宜昌市| 资中县| 会昌县| 常熟市| 武定县| 田阳县| 额济纳旗| 毕节市| 溧水县| 五家渠市| 延吉市| 武安市| 沛县| 当阳市| 新田县| 亚东县| 库车县| 称多县| 扶余县| 娄烦县| 萝北县| 德令哈市| 文昌市| 郧西县| 许昌县| 太康县| 大城县| 杭锦旗| 清涧县| 雅安市| 永兴县| 饶阳县| 英德市| 中阳县| 新密市| 花莲市| 阿巴嘎旗|