文章目錄
項目使用的Spring Cloud爲Hoxton版本,Spring Boot爲2.2.2.RELEASE版本
Spring Cloud入門系列彙總
摘要
Spring Cloud Alibaba 致力於提供微服務開發的一站式解決方案,Sentinel 作爲其核心組件之一,具有熔斷與限流等一系列服務保護功能,本文將對其用法進行詳細介紹。
Sentinel簡介
隨着微服務的流行,服務和服務之間的穩定性變得越來越重要。 Sentinel 以流量爲切入點,從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。
Sentinel具有如下特性:
- 豐富的應用場景:承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺,可以實時熔斷下游不可用應用;
- 完備的實時監控:同時提供實時的監控功能。可以在控制檯中看到接入應用的單臺機器秒級數據,甚至 500 臺以下規模的集羣的彙總運行情況;
- 廣泛的開源生態:提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Dubbo、gRPC 的整合;
- 完善的 SPI 擴展點:提供簡單易用、完善的 SPI 擴展點。您可以通過實現擴展點,快速的定製邏輯。
安裝Sentinel控制檯
Sentinel控制檯是一個輕量級的控制檯應用,它可用於實時查看單機資源監控及集羣資源彙總,並提供了一系列的規則管理功能,如流控規則、降級規則、熱點規則等。
我們先從官網下載Sentinel,這裏下載的是sentinel-dashboard-1.7.0.jar
文件,下載地址:https://github.com/alibaba/Sentinel/releas
下載完成後在命令行輸入如下命令運行Sentinel控制檯:
java -jar sentinel-dashboard-1.7.0.jar
Sentinel控制檯默認運行在8080端口上,登錄賬號密碼均爲sentinel
,通過如下地址可以進行訪問:http://localhost:8080
Sentinel控制檯可以查看單臺機器的實時監控數據。
創建sentinel-service模塊
這裏我們創建一個sentinel-service模塊,用於演示Sentinel的熔斷與限流功能。
在pom.xml中添加相關依賴,這裏我們使用Nacos作爲註冊中心,所以需要同時添加Nacos的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在application.yml中添加相關配置,主要是配置了Nacos和Sentinel控制檯的地址:
server:
port: 8401
spring:
application:
name: sentinel-service
cloud:
nacos:
# 配置Nacos地址
server-addr: http://localhost:8848
sentinel:
transport:
# 配置Sentinel dashborad地址
dashboard: http://localhost:8080
port: 8719
service-url:
user-service: http://nacos-user-service
management:
endpoints:
web:
exposure:
include: '*'
限流功能
Sentinel Starter 默認爲所有的 HTTP 服務提供了限流埋點,我們也可以通過使用@SentinelResource來自定義一些限流行爲。
創建RateLimitController類
用於測試熔斷和限流功能。
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/**
* 按資源名稱限流,需要指定限流處理邏輯
*
* @return
*/
@GetMapping("/byResource")
@SentinelResource(value = "byResource", blockHandler = "handleException")
public Result byResource() {
return new Result("按資源名稱限流", 200);
}
/**
* 按url限流,有默認的限流處理邏輯
*
* @return
*/
@GetMapping("byUrl")
@SentinelResource(value = "byUrl", blockHandler = "handleException")
public Result byUrl() {
return new Result("按url限流", 200);
}
public Result handleException(BlockException exception) {
return new Result(exception.getClass().getCanonicalName(), 200);
}
@GetMapping("/customBlockHandler")
@SentinelResource(value = "customBlockHandler", blockHandler = "handleException", blockHandlerClass = CustomBlockHandler.class)
public Result blockHandler() {
return new Result("限流成功", 200);
}
}
根據資源名稱限流
我們可以根據@SentinelResource註解中定義的value(資源名稱)來進行限流操作,但是需要指定限流處理邏輯。
流控規則可以在Sentinel控制檯進行配置,由於我們使用了Nacos註冊中心,我們先啓動Nacos和sentinel-service;
由於Sentinel採用的懶加載規則,需要我們先訪問下接口,Sentinel控制檯中才會有對應服務信息,我們先訪問下該接口:http://localhost:8401/rateLimit/byResource
在Sentinel控制檯配置流控規則,根據@SentinelResource註解的value值:
快速訪問上面的接口,可以發現返回了自己定義的限流處理信息:
根據URL限流
我們還可以通過訪問的URL來限流,會返回默認的限流處理信息。
在Sentinel控制檯配置流控規則,使用訪問的URL:
多次訪問該接口,會返回默認的限流處理結果:http://localhost:8401/rateLimit/byUrl
自定義限流處理邏輯
我們可以自定義通用的限流處理邏輯,然後在@SentinelResource中指定。
創建CustomBlockHandler類用於自定義限流處理邏輯:
public class CustomBlockHandler {
public Result handleException(BlockException exception) {
return new Result("自定義限流信息", 200);
}
}
在RateLimitController中使用自定義限流處理邏輯:
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/**
* 自定義通用的限流處理邏輯
*/
@GetMapping("/customBlockHandler")
@SentinelResource(value = "customBlockHandler", blockHandler = "handleException", blockHandlerClass = CustomBlockHandler.class)
public Result blockHandler() {
return new Result("限流成功", 200);
}
}
熔斷功能
Sentinel 支持對服務間調用進行保護,對故障應用進行熔斷操作,這裏我們使用RestTemplate來調用nacos-user-service服務所提供的接口來演示下該功能。
首先我們需要使用@SentinelRestTemplate來包裝下RestTemplate實例:
@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
添加CircleBreakerController類,定義對nacos-user-service提供接口的調用:
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {
private static final Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.user-service}")
private String userServiceUrl;
@GetMapping("/fallback/{id}")
// @SentinelResource(value = "fallback", fallback = "handleFallback")
public Result fallback(@PathVariable Long id) {
Result forObject = restTemplate.getForObject(userServiceUrl + "/user/{1}", Result.class, id);
System.out.println(forObject);
return forObject;
}
@GetMapping("/fallbackException/{id}")
@SentinelResource(value = "fallbackException", fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
public Result fallbackException(@PathVariable Long id) {
if (id == 1) {
throw new IndexOutOfBoundsException();
} else if (id == 2) {
throw new NullPointerException();
}
return restTemplate.getForObject(userServiceUrl + "/user/{1}", Result.class, id);
}
public Result handleFallback(Long id) {
return new Result("服務降級返回", 200);
}
public Result handleFallback2(Long id, Throwable e) {
LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
return new Result("服務降級返回", 200);
}
}
啓動nacos-user-service和sentinel-service服務:
由於我們並沒有在nacos-user-service中定義id爲4的用戶,所有訪問如下接口會返回服務降級結果:http://localhost:8401/breaker/fallback/4
{
"data": null,
"message": "服務降級返回",
"code": 200
}
由於我們使用了exceptionsToIgnore參數忽略了NullPointerException,所以我們訪問接口報空指針時不會發生服務降級:http://localhost:8401/breaker/fallbackException/2
與Feign結合使用
Sentinel也適配了Feign組件,我們使用Feign來進行服務間調用時,也可以使用它來進行熔斷。
首先我們需要在pom.xml中添加Feign相關依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在application.yml中打開Sentinel對Feign的支持:
# 打開sentinel對feign的支持
feign:
sentinel:
enabled: true
在應用啓動類上添加@EnableFeignClients啓動Feign的功能;
創建一個UserService接口,用於定義對nacos-user-service服務的調用:
@FeignClient(value = "nacos-user-service", fallback = UserFallbackService.class)
public interface UserService {
@PostMapping("/user/insert")
Result insert(@RequestBody User user);
@GetMapping("/user/{id}")
Result<User> getUser(@PathVariable Long id);
@GetMapping("/user/listUsersByIds")
Result<List<User>> listUsersByIds(@RequestParam List<Long> ids);
@GetMapping("/user/getByUsername")
Result<User> getByUsername(@RequestParam String username);
@PostMapping("/user/update")
Result update(@RequestBody User user);
@PostMapping("/user/delete/{id}")
Result delete(@PathVariable Long id);
}
創建UserFallbackService類實現UserService接口,用於處理服務降級邏輯:
@Component
public class UserFallbackService implements UserService {
@Override
public Result insert(User user) {
return new Result("調用失敗,服務被降級",500);
}
@Override
public Result<User> getUser(Long id) {
return new Result("調用失敗,服務被降級",500);
}
@Override
public Result<List<User>> listUsersByIds(List<Long> ids) {
return new Result("調用失敗,服務被降級",500);
}
@Override
public Result<User> getByUsername(String username) {
return new Result("調用失敗,服務被降級",500);
}
@Override
public Result update(User user) {
return new Result("調用失敗,服務被降級",500);
}
@Override
public Result delete(Long id) {
return new Result("調用失敗,服務被降級",500);
}
}
在UserFeignController中使用UserService通過Feign調用nacos-user-service服務中的接口:
@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService;
@PostMapping("/insert")
public Result insert(@RequestBody User user) {
return userService.insert(user);
}
@GetMapping("/{id}")
public Result<User> getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping("/listUsersByIds")
public Result<List<User>> listUsersByIds(@RequestParam List<Long> ids) {
return userService.listUsersByIds(ids);
}
@GetMapping("/getByUsername")
public Result<User> getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}
@PostMapping("/update")
public Result update(@RequestBody User user) {
return userService.update(user);
}
@PostMapping("/delete/{id}")
public Result delete(@PathVariable Long id) {
return userService.delete(id);
}
}
在啓動類SentinelServiceApplication添加@EnableFeignClients註解
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class SentinelServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SentinelServiceApplication.class, args);
}
}
調用如下接口會發生服務降級,返回服務降級處理信息:http://localhost:8401/user/4
{
"data": null,
"message": "調用失敗,服務被降級",
"code": 500
}
使用Nacos存儲規則
默認情況下,當我們在Sentinel控制檯中配置規則時,控制檯推送規則方式是通過API將規則推送至客戶端並直接更新到內存中。一旦我們重啓應用,規則將消失。下面我們介紹下如何將配置規則進行持久化,以存儲到Nacos爲例。
原理示意圖
首先我們直接在配置中心創建規則,配置中心將規則推送到客戶端;
Sentinel控制檯也從配置中心去獲取配置信息。
功能演示
先在pom.xml中添加相關依賴:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
修改application.yml配置文件,添加Nacos數據源配置:
spring:
application:
name: sentinel-service
cloud:
nacos:
# 配置Nacos地址
server-addr: http://localhost:8848
sentinel:
transport:
# 配置Sentinel dashborad地址
dashboard: http://localhost:8080
port: 8719
# 添加Nacos數據源配置
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
在Nacos中添加配置:
添加配置信息如下:
[
{
"resource": "/rateLimit/byUrl",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
相關參數解釋:
-
resource:資源名稱;
-
limitApp:來源應用;
-
grade:閾值類型,0表示線程數,1表示QPS;
-
count:單機閾值;
-
strategy:流控模式,0表示直接,1表示關聯,2表示鏈路;
-
controlBehavior:流控效果,0表示快速失敗,1表示Warm Up,2表示排隊等待;
-
clusterMode:是否集羣。
發現Sentinel控制檯已經有了如下限流規則:
快速訪問測試接口,可以發現返回了限流處理信息:
參考資料
Spring Cloud Alibaba 官方文檔:https://github.com/alibaba…
使用到的模塊
springcloud-learning
├── nacos-user-service -- 註冊到nacos的提供User對象CRUD接口的服務
└── sentinel-service -- sentinel功能測試服務