目录
源码
https://gitee.com/acelee723/acelee-alibaba-sentinelresource
参考
http://blog.didispace.com/spring-cloud-alibaba-sentinel-2-5/
背景
在之前的《Spring Cloud Alibaba(3)Sentinel接口限流整合入门 带源码》一文中,我们仅依靠引入Spring Cloud Alibaba对Sentinel的整合封装spring-cloud-starter-alibaba-sentinel
,就完成了对所有Spring MVC接口的限流控制。然而,在实际应用过程中,我们可能需要限流的层面不仅限于接口。可能对于某个方法的调用限流,对于某个外部资源的调用限流等都希望做到控制。那么,这个时候我们就不得不手工定义需要限流的资源点,并配置相关的限流策略等内容了。
今天这篇我们就来一起学习一下,如何使用@SentinelResource
注解灵活的定义控制资源以及如何配置控制策略。
自定义资源点
1.新建一个spring boot项目acelee-alibaba-sentinelresource,pom.xml文件添加sentinel依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.aceleeyy</groupId>
<artifactId>acelee-alibaba-sentinelresource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>acelee-alibaba-sentinelresource</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.在应用启动主类中增加注解支持的配置
package com.aceleeyy.aceleespringcloudalibaba;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class AceleeSpringcloudAlibabaApplication {
public static void main(String[] args) {
SpringApplication.run(AceleeSpringcloudAlibabaApplication.class, args);
}
// 注解支持的配置Bean
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
3.新建service和serviceImpl的包,对应增加接口类和实现类,添加一个doSomething()的方法