SpringBoot實戰電商項目mall(20k+star)地址:github.com/macrozheng/…java
Spring Cloud Alibaba 致力於提供微服務開發的一站式解決方案,Sentinel 做爲其核心組件之一,具備熔斷與限流等一系列服務保護功能,本文將對其用法進行詳細介紹。git
隨着微服務的流行,服務和服務之間的穩定性變得愈來愈重要。 Sentinel 以流量爲切入點,從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。github
Sentinel具備以下特性:web
Sentinel控制檯是一個輕量級的控制檯應用,它可用於實時查看單機資源監控及集羣資源彙總,並提供了一系列的規則管理功能,如流控規則、降級規則、熱點規則等。spring
咱們先從官網下載Sentinel,這裏下載的是sentinel-dashboard-1.6.3.jar
文件,下載地址:github.com/alibaba/Sen…json
下載完成後在命令行輸入以下命令運行Sentinel控制檯:bash
java -jar sentinel-dashboard-1.6.3.jar
複製代碼
sentinel
,經過以下地址能夠進行訪問:http://localhost:8080這裏咱們建立一個sentinel-service模塊,用於演示Sentinel的熔斷與限流功能。app
<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>
複製代碼
server:
port: 8401
spring:
application:
name: sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
sentinel:
transport:
dashboard: localhost:8080 #配置sentinel dashboard地址
port: 8719
service-url:
user-service: http://nacos-user-service
management:
endpoints:
web:
exposure:
include: '*'
複製代碼
Sentinel Starter 默認爲全部的 HTTP 服務提供了限流埋點,咱們也能夠經過使用@SentinelResource來自定義一些限流行爲。框架
用於測試熔斷和限流功能。ide
/** * 限流功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/** * 按資源名稱限流,須要指定限流處理邏輯 */
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult("按資源名稱限流", 200);
}
/** * 按URL限流,有默認的限流處理邏輯 */
@GetMapping("/byUrl")
@SentinelResource(value = "byUrl",blockHandler = "handleException")
public CommonResult byUrl() {
return new CommonResult("按url限流", 200);
}
public CommonResult handleException(BlockException exception){
return new CommonResult(exception.getClass().getCanonicalName(),200);
}
}
複製代碼
咱們能夠根據@SentinelResource註解中定義的value(資源名稱)來進行限流操做,可是須要指定限流處理邏輯。
流控規則能夠在Sentinel控制檯進行配置,因爲咱們使用了Nacos註冊中心,咱們先啓動Nacos和sentinel-service;
因爲Sentinel採用的懶加載規則,須要咱們先訪問下接口,Sentinel控制檯中才會有對應服務信息,咱們先訪問下該接口:http://localhost:8401/rateLimit/byResource
在Sentinel控制檯配置流控規則,根據@SentinelResource註解的value值:
咱們還能夠經過訪問的URL來限流,會返回默認的限流處理信息。
咱們能夠自定義通用的限流處理邏輯,而後在@SentinelResource中指定。
/** * Created by macro on 2019/11/7. */
public class CustomBlockHandler {
public CommonResult handleException(BlockException exception){
return new CommonResult("自定義限流信息",200);
}
}
複製代碼
/** * 限流功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {
/** * 自定義通用的限流處理邏輯 */
@GetMapping("/customBlockHandler")
@SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
public CommonResult blockHandler() {
return new CommonResult("限流成功", 200);
}
}
複製代碼
Sentinel 支持對服務間調用進行保護,對故障應用進行熔斷操做,這裏咱們使用RestTemplate來調用nacos-user-service服務所提供的接口來演示下該功能。
/** * Created by macro on 2019/8/29. */
@Configuration
public class RibbonConfig {
@Bean
@SentinelRestTemplate
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
複製代碼
/** * 熔斷功能 * Created by macro on 2019/11/7. */
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {
private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.user-service}")
private String userServiceUrl;
@RequestMapping("/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handleFallback")
public CommonResult fallback(@PathVariable Long id) {
return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
}
@RequestMapping("/fallbackException/{id}")
@SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
public CommonResult fallbackException(@PathVariable Long id) {
if (id == 1) {
throw new IndexOutOfBoundsException();
} else if (id == 2) {
throw new NullPointerException();
}
return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
}
public CommonResult handleFallback(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"服務降級返回",200);
}
public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
User defaultUser = new User(-2L, "defaultUser2", "123456");
return new CommonResult<>(defaultUser,"服務降級返回",200);
}
}
複製代碼
啓動nacos-user-service和sentinel-service服務:
因爲咱們並無在nacos-user-service中定義id爲4的用戶,全部訪問以下接口會返回服務降級結果:http://localhost:8401/breaker/fallback/4
{
"data": {
"id": -1,
"username": "defaultUser",
"password": "123456"
},
"message": "服務降級返回",
"code": 200
}
複製代碼
Sentinel也適配了Feign組件,咱們使用Feign來進行服務間調用時,也可使用它來進行熔斷。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
複製代碼
feign:
sentinel:
enabled: true #打開sentinel對feign的支持
複製代碼
在應用啓動類上添加@EnableFeignClients啓動Feign的功能;
建立一個UserService接口,用於定義對nacos-user-service服務的調用:
/** * Created by macro on 2019/9/5. */
@FeignClient(value = "nacos-user-service",fallback = UserFallbackService.class)
public interface UserService {
@PostMapping("/user/create")
CommonResult create(@RequestBody User user);
@GetMapping("/user/{id}")
CommonResult<User> getUser(@PathVariable Long id);
@GetMapping("/user/getByUsername")
CommonResult<User> getByUsername(@RequestParam String username);
@PostMapping("/user/update")
CommonResult update(@RequestBody User user);
@PostMapping("/user/delete/{id}")
CommonResult delete(@PathVariable Long id);
}
複製代碼
/** * Created by macro on 2019/9/5. */
@Component
public class UserFallbackService implements UserService {
@Override
public CommonResult create(User user) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"服務降級返回",200);
}
@Override
public CommonResult<User> getUser(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"服務降級返回",200);
}
@Override
public CommonResult<User> getByUsername(String username) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser,"服務降級返回",200);
}
@Override
public CommonResult update(User user) {
return new CommonResult("調用失敗,服務被降級",500);
}
@Override
public CommonResult delete(Long id) {
return new CommonResult("調用失敗,服務被降級",500);
}
}
複製代碼
/** * Created by macro on 2019/8/29. */
@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public CommonResult getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping("/getByUsername")
public CommonResult getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}
@PostMapping("/create")
public CommonResult create(@RequestBody User user) {
return userService.create(user);
}
@PostMapping("/update")
public CommonResult update(@RequestBody User user) {
return userService.update(user);
}
@PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
return userService.delete(id);
}
}
複製代碼
{
"data": {
"id": -1,
"username": "defaultUser",
"password": "123456"
},
"message": "服務降級返回",
"code": 200
}
複製代碼
默認狀況下,當咱們在Sentinel控制檯中配置規則時,控制檯推送規則方式是經過API將規則推送至客戶端並直接更新到內存中。一旦咱們重啓應用,規則將消失。下面咱們介紹下如何將配置規則進行持久化,以存儲到Nacos爲例。
首先咱們直接在配置中心建立規則,配置中心將規則推送到客戶端;
Sentinel控制檯也從配置中心去獲取配置信息。
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
複製代碼
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
複製代碼
[
{
"resource": "/rateLimit/byUrl",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
複製代碼
相關參數解釋:
發現Sentinel控制檯已經有了以下限流規則:
Spring Cloud Alibaba 官方文檔:github.com/alibaba/spr…
springcloud-learning
├── nacos-user-service -- 註冊到nacos的提供User對象CRUD接口的服務
└── sentinel-service -- sentinel功能測試服務
複製代碼
mall項目全套學習教程連載中,關注公衆號第一時間獲取。