好的,以下是一個簡單的Spring Cloud整合Sentinel的代碼示例:
- 首先,在pom.xml中添加以下依賴:
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId><version>2.2.0.RELEASE</version>
</dependency>
- 然后,在Spring Boot應用程序的主類中添加@EnableSentinel注解以啟用Sentinel:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableSentinel
public class MyApp {public static void main(String[] args) {SpringApplication.run(MyApp.class, args);}
}
- 接下來,配置Sentinel的規則。這里使用注解方式定義規則,示例代碼如下:
@RestController
public class MyController {@GetMapping("/hello")@SentinelResource(value = "hello", blockHandler = "handleBlock", fallback = "handleFallback")public String hello() {return "Hello, world!";}public String handleBlock(BlockException ex) {return "Blocked by Sentinel: " + ex.getClass().getSimpleName();}public String handleFallback(Throwable t) {return "Error occurred: " + t.getMessage();}
}
上面代碼中,@SentinelResource注解表示該方法需要受到Sentinel的保護。其中,value屬性表示流控規則的名稱,在Sentinel控制臺中可以看到;blockHandler屬性表示當方法被流控時需要執行的方法;fallback屬性表示當方法發生異常時需要執行的方法。
- 最后,啟動應用程序并訪問/hello接口,觀察Sentinel控制臺是否正確統計了接口訪問情況。
以上就是一個簡單的Spring Cloud整合Sentinel的代碼示例。需要注意的是,在實際項目中,還需要根據業務需求配置Sent