实例演示1:通过Sentinel实现限流
- 创建SentinelDemo的Maven项目,配置pom文件:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
</dependencies>
package prj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
- 编写application.properties配置文件:
spring.application.name=SentinelDemo
# 与Sentinel控制台交互的端口
spring.cloud.sentinel.transport.port=9000
# sentinel控制台的工作地址和端口
spring.cloud.sentinel.transport.dashboard=localhost:8090
- 编写Controller控制类ContrllerForLimit:
@RestController
public class ControllerForLimit {
@RequestMapping("/sayHello")
@SentinelResource(value = "sayHello")
public String sayHello() {
return "Hello Sentinel";
}
@RequestMapping("/useSentinel")
@SentinelResource(value = "useSentinel")
public String useSentinel() {
return "Use Sentinel";
}
}
实例演示2:实现热点限流效果
- 在SentinelDemo项目的基础上,新增控制类ContrllerForHotPot:
@RestController
public class ControllerForHotSpot {
@RequestMapping("/buyItem")
@SentinelResource(value = "buyItem")
public String buyItem(@RequestParam(value = "item", required = false) String item,
@RequestParam(value = "price", required = false) String price) {
return "Hot Spot Demo";
}
}
实例演示3:实现熔断限流效果
- 在SentinelDemo项目的基础上,新增控制类ContrllerForFusing:
@RestController
public class ControllerForFusing {
@RequestMapping("/testFusing")
@SentinelResource(value = "testFusing")
public String testFusing() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Test Fusing";
}
}
- 控制台设置慢调用比例参数后,编写测试类,运行项目观察熔断效果:
class RequestThread extends Thread{
public void run() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/testFusing", String.class);
System.out.println(entity.getBody());
}
}
public class TestFusing {
public static void main(String[] args){
for(int i = 0;i<1000;i++) {
new RequestThread().start();
}
}
}
实例演示4:实现服务降级效果
- 在控制类ContrllerForLimit,添加limitForHandle的服务方法
@RestController
public class ControllerForLimit {
@RequestMapping("/sayHello")
@SentinelResource(value = "sayHello")
public String sayHello() {
return "Hello Sentinel";
}
@RequestMapping("/useSentinel")
@SentinelResource(value = "useSentinel")
public String useSentinel() {
return "Use Sentinel";
}
@RequestMapping("/limitForHandler")
@SentinelResource(value = "limitForHandler",fallback ="handleException")
public String limitForHandler() {
return "limitForHandler";
}
public String handleException() {
return "handler limit Exception";
}
}