@Sentinel
在Spring Cloud中,Sentinel是一个流量控制、熔断降级的组件。你可以通过配置和注解的方式将Sentinel与RestTemplate结合使用,实现熔断降级功能。以下是一个基本的示例:
1. 引入依赖
首先,在你的pom.xml
文件中引入必要的依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 配置RestTemplate
在你的Spring Boot应用程序中配置RestTemplate,并添加Sentinel的支持:
import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3. 配置熔断降级处理逻辑
你需要定义一个类来处理熔断降级的逻辑:
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Component;
@Component
public class RestTemplateFallbackHandler {
public static String handleException(BlockException ex) {
return "Request was blocked by Sentinel: " + ex.getClass().getSimpleName();
}
public static String fallback(Throwable throwable) {
return "Fallback: " + throwable.getMessage();
}
}
4. 使用RestTemplate进行请求
在你的业务代码中使用RestTemplate进行请求,并配置熔断降级处理逻辑:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/test")
public String test() {
String url = "http://example-service/test";
return restTemplate.getForObject(url, String.class);
}
}
5. 配置Sentinel规则
你可以通过配置文件或者Sentinel Dashboard来配置流量控制和熔断降级规则。以下是一个简单的配置文件示例:
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: sentinel-rules
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
在Nacos中配置流量控制规则:
[
{
"resource": "http://example-service/test",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
6. 启动应用
可以通过访问http://localhost:8080
来查看和管理Sentinel的规则。
Hystrix和Resilience4j
在Spring Cloud中,熔断和降级是通过Hystrix或Resilience4j等库来实现的。以下是使用Hystrix和Resilience4j实现RestTemplate熔断和降级的示例。
使用Hystrix实现RestTemplate熔断和降级
-
添加依赖
在
pom.xml
中添加Hystrix依赖:<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
-
启用Hystrix
在Spring Boot应用的主类上添加
@EnableHystrix
注解:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; @SpringBootApplication @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-
创建RestTemplate Bean
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
-
使用HystrixCommand注解
在需要熔断和降级的方法上使用
@HystrixCommand
注解:import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class MyService { @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "fallback") public String callExternalService() { return restTemplate.getForObject("http://external-service/api", String.class); } public String fallback() { return "Fallback response"; } }
使用Resilience4j实现RestTemplate熔断和降级
-
添加依赖
在
pom.xml
中添加Resilience4j依赖:<dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot2</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
-
配置Resilience4j
在
application.yml
中配置Resilience4j:resilience4j: circuitbreaker: instances: myService: registerHealthIndicator: true slidingWindowSize: 10 minimumNumberOfCalls: 5 failureRateThreshold: 50 waitDurationInOpenState: 10000
-
创建RestTemplate Bean
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
-
使用CircuitBreaker注解
在需要熔断和降级的方法上使用
@CircuitBreaker
注解:import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class MyService { @Autowired private RestTemplate restTemplate; @CircuitBreaker(name = "myService", fallbackMethod = "fallback") public String callExternalService() { return restTemplate.getForObject("http://external-service/api", String.class); } public String fallback(Throwable t) { return "Fallback response"; } }
以上是使用Hystrix和Resilience4j实现RestTemplate熔断和降级的基本步骤。你可以根据具体需求进行调整和扩展。