一、前言:
近期在设计企业级服务网关时,有流控、熔断相关的需求,在查找相关资料时,很多资料都写的一点,很难运行跑起来,导致浪费了太多的时间,近期功能设计完了,写篇文章,毫无吝啬的分享给大家,希望对大家的学习有所帮助。
二、环境准备工作:
1、nacos部署:
下载地址:https://github.com/alibaba/nacos/releases
修改bin/startup.bat ,修改内容如下:
set MODE="standalone"
2、sentinel部署:
下载jar包:笔者下载的如下版本;
启动方式java -jar sentinel-dashboard-1.8.3.jar
三、相关集成代码:
1、代码:
@EnableDiscoveryClient
@SpringBootApplication
public class SpringSentinelApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSentinelApplication.class, args);
}
}
@RestController
public class SentinelController {
@RequestMapping("/hello")
@SentinelResource(value="hello", blockHandler = "sayHello")// 添加注解
@ResponseBody
public String hello() {
return test();
}
@RequestMapping("/sgcc")
@SentinelResource(value="sgcc", blockHandler = "saySgcc")// 添加注解
@ResponseBody
public String sgcc() {
return test();
}
@ResponseBody
public String sayHello(BlockException e) {
e.printStackTrace();
return "sayHello被限流了" ;
}
@ResponseBody
public String saySgcc(BlockException e) {
e.printStackTrace();
return "saySgcc被限流了" ;
}
public String test()
{
return "test";
}
}
2、配置文件:
A、application.yml
server:
port: 8089
yan B、bootstrap.yml
spring:
application:
name: sentinel-app
cloud:
nacos:
discovery:
server-addr: http://localhost:8848
enabled: true
namespace: public
group: DEFAULT_GROUP
access-key: nacos
secret-key: nacos
config:
server-addr: http://localhost:8848
file-extension: yaml
group: DEFAULT_GROUP
namespace: public
access-key: nacos
secret-key: nacos
username:
sentinel:
eager: true
transport:
dashboard: localhost:8080
port: 8719
clientIp: 192.168.115.1
datasource:
ds1:
nacos:
server-addr: localhost:8848
group-id: DEFAULT_GROUP
data-id: sentinel-app
data-type: json
rule-type: flow四、功能验证:
1、nacos配置流控信息:

[
{
"resource": "hello",
"limitApp": "default",
"grade": 1,
"count": 3,
"strategy": 0,
"controlBehavior": 0,
"clusterMode":false
},{
"resource": "sgcc",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode":false
}
]2、查看sentinel控制面板,检查nacos配置信息是否pull到sentinel内存:
http://localhost:8080/#/dashboard

3、功能验证:
流控信息展示:
版权声明:本文为jason_jiahongfei原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。