spring cloud nacos 三 Sentinel的使用
一.Spring Cloud中使用Sentinel
1.在服务提供者pom.xml 加入 spring-cloud-starter-alibaba-sentine
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
2.application.yml
server:
port: 8762
# 注意:下面注释了是因为 消费者可能会因为配置了context-path 而调用请求不到提供者的服务
# servlet:
# context-path: /nacos-provider
spring:
application:
name: nacos-provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
port: 8719
dashboard: localhost:8080
3.在controller中加入注解
package com.sunup.practice.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class ProviderController {
@GetMapping("/hello")
@SentinelResource(value="hello")
public String hi(@RequestParam(value = "name", defaultValue = "nacos", required = false) String name) {
log.debug(name);
return "hello" + name;
}
}
4启动sentinel 下载地址 https://github.com/alibaba/Sentinel/releases 我下载的1.6.2版本 启动 java -jar sentinel-dashboard-1.6.2.jar 访问 http://localhost:8080
5.在流控规则添加规则
6.然后重启服务提供者访问http://localhost:8761/hello 每秒多访问几次就会出现
Blocked by Sentinel (flow limiting)
二、在FeignClient中使用Sentinel
1.在消费者pom.xml 中加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
2.application.yml添加配置
server:
port: 8763
# 注意:下面注释了是因为 消费者可能会因为配置了context-path 而调用请求不到提供者的服务
# servlet:
# context-path: /nacos-consuer
spring:
application:
name: nacos-consuer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
port: 8719
dashboard: localhost:8080
feign.sentinel.enabled: true
3.还是添加规则
4.访问http://localhost:8763/helloFeign