Back to Javatutorial

SpringCloudAlibabaSentinel

docs/Spring全家桶/SpringCloudAlibaba/SpringCloudAlibabaSentinel.md

1.0.012.8 KB
Original Source

ժҪ

Spring Cloud Alibaba ṩ΢񿪷һվʽSentinel Ϊ֮һ۶һϵз񱣻ܣĽ÷ϸܡ

Sentinel

΢Уͷ֮ȶԱԽԽҪ Sentinel Ϊ㣬ơ۶Ͻϵͳرȶάȱȶԡ

Sentinel:

  • ḻӦóн˰Ͱͽ 10 ˫ʮһĺijɱʵʱ۶βӦã
  • 걸ʵʱأͬʱṩʵʱļعܡڿ̨пӦõĵ̨뼶ݣ 500 ̨¹ģļȺĻ
  • 㷺ĿԴ̬ṩ伴õԴ/ģ飬 Spring CloudDubbogRPC ϣ
  • Ƶ SPI չ㣺ṩáƵ SPI չ㡣ͨʵչ㣬ٵĶ߼

װSentinel̨

Sentinel̨һĿ̨Ӧãʵʱ鿴ԴؼȺԴܣṩһϵеĹܣع򡢽ȵȡ

java -jar sentinel-dashboard-1.6.3.jar
ƴ

  • Sentinel̨Բ鿴̨ʵʱݡ

sentinel-serviceģ

Ǵһsentinel-serviceģ飬ʾSentinel۶ܡ

  • pom.xmlʹNacosΪעģҪͬʱNacos
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    spring-cloud-starter-alibaba-nacos-discovery
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    spring-cloud-starter-alibaba-sentinel
</dependency>
ƴ
  • application.ymlãҪNacosSentinel̨ĵַ
server:
  port: 8401
spring:
  application:
    name: sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacosַ
    sentinel:
      transport:
        dashboard: localhost:8080 #sentinel dashboardַ
        port: 8719
service-url:
  user-service: http://nacos-user-service
management:
  endpoints:
    web:
      exposure:
        include: '*'
ƴ

Sentinel Starter ĬΪе HTTP ṩ㣬Ҳͨʹ@SentinelResourceԶһЩΪ

RateLimitController

ڲ۶Ϻܡ

/**
 * 
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /**
     * ԴҪָ߼
     */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult("Դ", 200);
    }

    /**
     * URLĬϵ߼
     */
    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl",blockHandler = "handleException")
    public CommonResult byUrl() {
        return new CommonResult("url", 200);
    }

    public CommonResult handleException(BlockException exception){
        return new CommonResult(exception.getClass().getCanonicalName(),200);
    }

}
ƴ

Դ

ǿԸ@SentinelResourceעжvalueԴƣҪָ߼

  • ٷĽӿڣԷַԼϢ

URL

ǻͨʵURL᷵ĬϵϢ

  • Sentinel̨عʹ÷ʵURL

Զ߼

ǿԶͨõ߼Ȼ@SentinelResourceָ

  • CustomBlockHandlerԶ߼
/**
 * Created by macro on 2019/11/7.
 */
public class CustomBlockHandler {

    public CommonResult handleException(BlockException exception){
        return new CommonResult("ԶϢ",200);
    }
}
ƴ
  • RateLimitControllerʹԶ߼
/**
 * 
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /**
     * Զͨõ߼
     */
    @GetMapping("/customBlockHandler")
    @SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
    public CommonResult blockHandler() {
        return new CommonResult("ɹ", 200);
    }

}
ƴ

۶Ϲ

Sentinel ֶ֧ԷýбԹӦý۶ϲʹRestTemplatenacos-user-serviceṩĽӿʾ¸ùܡ

  • Ҫʹ@SentinelRestTemplateװRestTemplateʵ
/**
 * Created by macro on 2019/8/29.
 */
@Configuration
public class RibbonConfig {

    @Bean
    @SentinelRestTemplate
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
ƴ
  • CircleBreakerController࣬nacos-user-serviceṩӿڵĵã
/**
 * ۶Ϲ
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {

    private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
    @Autowired
    private RestTemplate restTemplate;
    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @RequestMapping("/fallback/{id}")
    @SentinelResource(value = "fallback",fallback = "handleFallback")
    public CommonResult fallback(@PathVariable Long id) {
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    @RequestMapping("/fallbackException/{id}")
    @SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
    public CommonResult fallbackException(@PathVariable Long id) {
        if (id == 1) {
            throw new IndexOutOfBoundsException();
        } else if (id == 2) {
            throw new NullPointerException();
        }
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult handleFallback(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"񽵼",200);
    }

    public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
        LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
        User defaultUser = new User(-2L, "defaultUser2", "123456");
        return new CommonResult<>(defaultUser,"񽵼",200);
    }
}
ƴ
{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "񽵼",
	"code": 200
}
ƴ

Feignʹ

SentinelҲFeignʹFeignзʱҲʹ۶ϡ

  • Ҫpom.xmlFeign
<dependency>
    <groupId>org.springframework.cloud</groupId>
    spring-cloud-starter-openfeign
</dependency>
ƴ
  • application.ymlдSentinelFeign֧֣
feign:
  sentinel:
    enabled: true #sentinelfeign֧
ƴ
  • Ӧ@EnableFeignClientsFeignĹܣ

  • һUserServiceӿڣڶnacos-user-serviceĵã

/**
 * Created by macro on 2019/9/5.
 */
@FeignClient(value = "nacos-user-service",fallback = UserFallbackService.class)
public interface UserService {
    @PostMapping("/user/create")
    CommonResult create(@RequestBody User user);

    @GetMapping("/user/{id}")
    CommonResult<User> getUser(@PathVariable Long id);

    @GetMapping("/user/getByUsername")
    CommonResult<User> getByUsername(@RequestParam String username);

    @PostMapping("/user/update")
    CommonResult update(@RequestBody User user);

    @PostMapping("/user/delete/{id}")
    CommonResult delete(@PathVariable Long id);
}
ƴ
  • UserFallbackServiceʵUserServiceӿڣڴ񽵼߼
/**
 * Created by macro on 2019/9/5.
 */
@Component
public class UserFallbackService implements UserService {
    @Override
    public CommonResult create(User user) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"񽵼",200);
    }

    @Override
    public CommonResult<User> getUser(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"񽵼",200);
    }

    @Override
    public CommonResult<User> getByUsername(String username) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"񽵼",200);
    }

    @Override
    public CommonResult update(User user) {
        return new CommonResult("ʧܣ񱻽",500);
    }

    @Override
    public CommonResult delete(Long id) {
        return new CommonResult("ʧܣ񱻽",500);
    }
}
ƴ
  • UserFeignControllerʹUserServiceͨFeignnacos-user-serviceеĽӿڣ
/**
 * Created by macro on 2019/8/29.
 */
@RestController
@RequestMapping("/user")
public class UserFeignController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public CommonResult getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @GetMapping("/getByUsername")
    public CommonResult getByUsername(@RequestParam String username) {
        return userService.getByUsername(username);
    }

    @PostMapping("/create")
    public CommonResult create(@RequestBody User user) {
        return userService.create(user);
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        return userService.update(user);
    }

    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        return userService.delete(id);
    }
}
ƴ
{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "񽵼",
	"code": 200
}
ƴ

ʹNacos洢

Ĭ£Sentinel̨ùʱ̨͹ʽͨAPIͻ˲ֱӸµڴСһӦãʧǽνùг־ûԴ洢NacosΪ

ԭʾͼ

  • ֱĴĽ͵ͻˣ

  • Sentinel̨ҲȥȡϢ

ʾ

  • pom.xml
<dependency>
    <groupId>com.alibaba.csp</groupId>
    sentinel-datasource-nacos
</dependency>
ƴ
  • ޸application.ymlļNacosԴã
spring:
  cloud:
    sentinel:
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-sentinel
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow
ƴ
  • Nacosã

  • Ϣ£
[
    {
        "resource": "/rateLimit/byUrl",
        "limitApp": "default",
        "grade": 1,
        "count": 1,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]
ƴ
  • زͣ

    • resourceԴƣ
    • limitAppԴӦã
    • gradeֵͣ0ʾ߳1ʾQPS
    • countֵ
    • strategyģʽ0ʾֱӣ1ʾ2ʾ·
    • controlBehaviorЧ0ʾʧܣ1ʾWarm Up2ʾŶӵȴ
    • clusterModeǷȺ
  • Sentinel̨Ѿ

  • ٷʲԽӿڣԷַϢ

ο

Spring Cloud Alibaba ٷĵgithub.com/alibaba/spr

ʹõģ

springcloud-learning
 nacos-user-service -- עᵽnacosṩUserCRUDӿڵķ
 sentinel-service -- sentinelܲԷ
ƴ

ĿԴַ

github.com/macrozheng/

ߣMacroZheng ӣhttps://juejin.cn/post/6844903999876022279 Դϡ ȨСҵתϵ߻Ȩҵתע

ο

https://lijunyi.xyz/docs/SpringCloud/SpringCloud.html#_2-2-x-%E5%88%86%E6%94%AF https://mp.weixin.qq.com/s/2jeovmj77O9Ux96v3A0NtA https://juejin.cn/post/6931922457741770760 https://github.com/D2C-Cai/herring http://c.biancheng.net/springcloud