【SpringCloud】Sentinel配置及使用

一、下载最新版Sentinel:

https://github.com/alibaba/Sentinel/releases

 

下载后以Jar包运行。

二、在需要限流的服务端添加配置:

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
<!--version 1.8.3-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

编辑application.yml,添加配置:

spring:
  cloud:
    nacos:
      discovery:
        #nacos server
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
  application:
    name: provider
server:
  port: 8081

management:
  endpoints:
    web:
      exposure:
        exclude: '*'

三、在controller 层编写测试服务请求类

package com.example.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class providerController {

    @Value("${server.port}")
    private String port;
    @GetMapping("/index")
    public String index(){
        return this.port;
    }

    @GetMapping("/list")
    public String list(){
        return "list";
    }
}

四、启动服务层,浏览器访问测试类方法,Sentinel默认启动在8080端口。

 

 添加限流规则:

 

 编写测试类测试限流效果:

package com.example.provider;

import org.springframework.web.client.RestTemplate;

public class test {
    public static void main(String[] args) throws InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        for (int i = 0; i < 1000; i++) {
            restTemplate.getForObject("http://localhost:8081/list",String.class);
            Thread.sleep(200);
        }
    }
}

测试前请求返回端口号:

 

 启动测试类,显示限流成功:

 

完毕!

 

posted @ 2022-03-09 22:49  小李不背锅  阅读(467)  评论(0编辑  收藏  举报