Sentinel dashboard的使用;Nacos保存Sentinel限流规则

Sentinel dashboard的使用

往期文章

  1. Nacos环境搭建
  2. Nacos注册中心的使用
  3. Nacos配置中心的使用
  4. Sentinel 容灾中心的使用

参考文档

Sentinel · alibaba/spring-cloud-alibaba Wiki · GitHub

限流结果

Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第1张图片

下载sentinel-dashboard

github地址:Sentinel/sentinel-dashboard at master · alibaba/Sentinel · GitHub

启动脚本

创建sentinel-dashboard的启动脚本,并添加如下信息:

java -jar -Dserver.port=8350 -Dcsp.sentinel.dashboard.server=localhost:8350 -Dproject.name=sentinel-dashboard --add-exports=java.base/sun.net.util=ALL-UNNAMED sentinel-dashboard-1.8.4.jar

目录:
Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第2张图片

Jar(客户端)



<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cspgroupId>
	<artifactId>sentinel-transport-simple-httpartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>

<dependency>
	<groupId>org.springframework.cloudgroupId>
	<artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-actuatorartifactId>
dependency>

yml

注意:sentinel-dashboard默认会在8720端口接收注册服务的数据,所以dashboard使用的端口和接收数据的端口不要一样。

消费者

server:
  port: 8581
spring:
  application:
	name: nacos-consumer
  cloud:
	nacos:
	  config:
		group: DEFAULT_GROUP
		server-addr: localhost:8848
	sentinel:
	  transport:
		port: 8720
		dashboard: localhost:8350
	  eager: true
  config:
	import:
	  # 父类配置要放在前面,相同的项会被后面的配置覆盖
	  - optional:nacos:nacos-discovery.yaml
management:
  endpoints:
	web:
	  exposure:
		include: '*'

nacos-discovery.yml

spring:
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        username: devilvan
        password: 741258963hjkl
        failure-tolerance-enabled: true

Sentinel Dashboard的使用

1. 关闭服务端硬编码的限流规则

服务端的代码参考:Sentinel 容灾中心的使用
Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第3张图片

2. 在dashboard中设置限流规则(不推荐)

不推荐的原因,客户端、服务端重启后规则不会保存
Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第4张图片
Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第5张图片

3. 限流效果:

Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第6张图片

Nacos配置并保存Sentinel限流规则

步骤

  1. 引入sentinel和sentinel dashboard相关依赖
  2. 服务端给对应controller添加@SentinelResource注解,并定义一个限流/熔断处理类负责处理该resource的限流/熔断逻辑(注:方法必须有static修饰)。
  3. Nacos配置中心保存sentinel resource的配置信息,即限流规则

Jar(服务端)



<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-circuitbreaker-sentinelartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cspgroupId>
	<artifactId>sentinel-transport-simple-httpartifactId>
dependency>
<dependency>
	<groupId>com.alibaba.cspgroupId>
	<artifactId>sentinel-datasource-nacosartifactId>
	<version>${sentinel-version}version>
dependency>
<dependency>
	<groupId>com.alibaba.cspgroupId>
	<artifactId>sentinel-spring-webmvc-adapterartifactId>
	<version>${sentinel-version}version>
dependency>
<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-webfluxartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>

<dependency>
	<groupId>com.alibaba.cloudgroupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>

yml(服务端)

server:
  port: 8481
spring:
  application:
	name: nacos-provider
  cloud:
	nacos:
	  config:
		group: DEFAULT_GROUP
		server-addr: localhost:8848
	  discovery:
		server-addr: localhost:8848
		username: devilvan
		password: 741258963hjkl
	sentinel:
	  transport:
		port: 8720
		dashboard: localhost:8350
	  eager: true
	  datasource:
		echo:
		  nacos:
			server-add: ${spring.cloud.nacos.config.server-addr}
			groupId: ${spring.cloud.nacos.config.group}
			dataId: ${spring.application.name}-rules
			rule-type: flow
			data-type: json
  config:
	import:
	  # 父类配置要放在前面,相同的项会被后面的配置覆盖
	  - optional:nacos:nacos-discovery.yaml
management:
  endpoints:
	web:
	  exposure:
		include: '*'

Nacos配置并保存Sentinel限流规则

1. Nacos配置中心添加配置文件

注:建议单独起resource的名字,不要将路由信息当做resource

Sentinel dashboard的使用;Nacos保存Sentinel限流规则_第7张图片

[
	{
		"resource": "echo",
		"limitApp": "default",
		"grade": 1,
		"count": 1,
		"strategy": 0,
		"controlBehavior": 0,
		"clusterMode": false
	},
	{
		"resource": "echo2",
		"limitApp": "default",
		"grade": 1,
		"count": 1,
		"strategy": 0,
		"controlBehavior": 0,
		"clusterMode": false
	}
]

2. 服务端后台代码

注意:echo2()方法是通过代码层面的try catch来进行限流/熔断的,在nacos配置中定义的echo2的resource不能在该处添加@SentinelResource注解

/**
 * @Description Nacos生产者 控制层
 */
@RestController
@RequestMapping(value = "nacosProviderController")
public class NacosProviderController {
	@Resource(name = "nacosProviderServiceImpl")
	private NacosProviderService nacosProviderService;

	@GetMapping(value = "/echo/{str}")
	@SentinelResource(value = "echo", fallback = "echoFallback", fallbackClass = EchoFallback.class,
			blockHandler = "echoBlockHandler", blockHandlerClass = EchoFallback.class)
	public ResultMessage<String> echo(@PathVariable String str) {
		return nacosProviderService.echo(str);
	}

	@GetMapping(value = "/echo2/{str}")
	public ResultMessage<String> echo2(@PathVariable String str) {
		return nacosProviderService.echo2(str);
	}
}

3. 限流/熔断处理类

注意:该类中的限流/熔断方法必须static修饰

/**
 * @Description echo方法 异常回调类
 */
public class EchoFallback {
	/**
	 * 遇到异常走的逻辑
	 *
	 * @param str 原方法的参数
	 * @param e   异常信息
	 * @return 异常回调方法返回值,和原方法返回值一致
	 */
	public static ResultMessage<String> echoFallback(String str, Throwable e) {
		ResultMessage<String> resultMessage = new ResultMessage<>();
		String message = "熔断-echo方法调用异常,str: " + str + "\n" + e;
		resultMessage.setMessage(message);
		return resultMessage;
	}

	/**
	 * 方法限流逻辑
	 *
	 * @param str 原方法的参数
	 * @param e   异常信息
	 * @return 限流回调方法返回值,和原方法返回值一致
	 */
	public static ResultMessage<String> echoBlockHandler(String str, BlockException e) {
		ResultMessage<String> resultMessage = new ResultMessage<>();
		String message = "限流-echo方法进行 限流,str: " + str + "\n" + e;
		resultMessage.setMessage(message);
		return resultMessage;
	}
}

4. 生产者业务逻辑代码

注:echo2()方法中使用的是sentinel的api实现限流,高亮的部分需要指定配置文件中已存在,或在代码中定义限流规则的resource,即"echo2"资源需要对应上方Nacos配置文件中的resource。

/**
 * @Description Nacos生产者 业务逻辑实现类
 */
@Service
public class NacosProviderServiceImpl implements NacosProviderService {
	/**
	 * 测试限流/熔断的方法
	 *
	 * @param str 原方法的参数
	 * @return 回调
	 */
	@Override
	public ResultMessage<String> echo(String str) {
		ResultMessage<String> resultMessage = new ResultMessage<>();
		if ("devilvan".equals(str)) {
			String msg = "Hello Nacos Discovery " + str;
			resultMessage.setMessage(msg);
		} else {
			throw new RuntimeException();
		}
		return resultMessage;
	}

	/**
	 * 测试sentinel设置资源并使用的方法
	 *
	 * @param str 入参字符串
	 * @return 回调
	 */
	@Override
	public ResultMessage<String> echo2(String str) {
		String resource = "echo2";
		ResultMessage<String> resultMessage = new ResultMessage<>();
		Entry entry = null;
		try {
			entry = SphU.entry(resource);
			if ("devilvan".equals(str)) {
				String msg = "Hello Nacos Discovery " + str;
				resultMessage.setMessage(msg);
			} else {
				throw new RuntimeException();
			}
		} catch (BlockException e) {
			String msg = "限流-echo2方法调用异常,str: " + str + "\n" + e;
			resultMessage.setMessage(msg);
		} catch (Exception e) {
			String msg = "熔断-echo2方法调用异常,str: " + str + "\n" + e;
			resultMessage.setMessage(msg);
		} finally {
			if (entry != null) {
				entry.exit();
			}
		}
		return resultMessage;
	}
}

你可能感兴趣的:(Spring,Cloud,Alibaba,sentinel,spring,cloud,spring,boot)