课堂笔记20230829

亮子 2023-08-29 03:59:11 10379 0 0 0

sentinel下载

https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar

运行sentinel

java -Dserver.port=8081 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.6.jar

图片alt

访问sentinel控制台

修改配置文件

spring:
  application:
    name: server-shop-user
  cloud:
    sentinel:
      transport:
        dashboard: 127.0.0.1:8081
        port: 8719

图片alt

重启微服务

图片alt

通过注解来实现熔断和降级

1)、添加配置类

package com.bw2102a.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 军哥
 * @version 1.0
 * @description: SentinelAspectConfiguration
 * @date 2023/8/29 16:04
 */

@Configuration
public class SentinelAspectConfiguration
{
    @Bean
    public SentinelResourceAspect sentinelResourceAspect()
    {
        return new SentinelResourceAspect();
    }
}

2)、使用注解管理接口

    @SentinelResource(value = "sentinel", blockHandler = "blockHandlerForSentinel")
    @PostMapping(value = "/sentinel")
    public ResultVo sentinel() {

        // 正常流程
        long millis = System.currentTimeMillis();
        log.info("helloWorld="+millis);

        return ResultVo.SUCCESS("hello,world:" + millis);
    }

    public ResultVo blockHandlerForSentinel(BlockException blockException) {
        log.error("系统繁忙,请稍后再试!");
        String resource = blockException.getRule().getResource();
        System.out.println("资源名称:"+resource);
        return ResultVo.FAILED(500, "系统繁忙,请稍后再试!");
    }

有两个坑:

图片alt

sentinel的使用注意事项

  • 熔断函数的参数必须和原函数一致,并且在最后加上BlockException
  • 熔断函数的返回值必须和原函数返回值类型有一致
    @PostMapping(value = "/login")
    @SentinelResource(value = "sentinelLogin", blockHandler = "blockHandlerForLogin")
    public ResultVo login(@RequestBody UserLoginVo userLoginVo) {
        return tbUserService.login(userLoginVo);
    }
	
    public ResultVo blockHandlerForLogin(@RequestBody UserLoginVo userLoginVo, BlockException blockException) {
        log.error("登录接口:熔断了");
        System.out.println(blockException.getRule().getResource());
        return ResultVo.FAILED(500, "系统繁忙,稍后再试!");
    }