Sentinel fuse Feign and Ribbon

Please see gitee for the entire project: https://gitee.com/xwb1056481167/spring-cloud

Sentinel installation and project integration: https://blog.csdn.net/www1056481167/article/details/113679945

Related projects Ribbon: cloudalibaba-provider-payment9003, cloudalibaba-provider-payment9004

Feign:cloudalibaba-consumer-nacos-order84

For configuration and installation of nacos, please go to: https://blog.csdn.net/www1056481167/article/details/113612177 view

Ribbon fuse

Service provider 9003,9004

1. Create new cloudalibaba-provider-payment9003 (the same below 9004)

<!-- alibaba nacos 服务端 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 引入api 公共包 -->
<dependency>
    <groupId>org.xwb.springcloud</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2 、 l 配置

server:
  port: 9002
spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
management:
  endpoints:
    web:
      exposure:
        include:  '*'

3. The main startup class

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain9002.class, args);
    }
}

4、controller

@RestController
public class PaymentController {
    @Value("\${server.port}")
    private String serverPort;
    public static HashMap<Long, Payment> hashMap = new HashMap<>();
    static {
        hashMap.put(1l, new Payment(1L, "210374208734KJEWFKW0U20sklfw0uor023u4"));
        hashMap.put(2l, new Payment(2L, "3498hofwsefhls93984rfhseohf2890343rwe"));
        hashMap.put(3l, new Payment(3L, "09snkjdfhjoiwhefdsnfjkhweo5235wefhwee"));
    }
    @GetMapping("/paymentSQL/{id}")
    public CommonResult paymentSQL(@PathVariable("id") Long id) {
        Payment payment = hashMap.get(id);
        CommonResult<Payment> result = new CommonResult<>(200, "from mysql,serverPort" + serverPort, payment);
        return result;
    }
}

Service consumer cloudalibaba-consumer-nacos-order84

1 、 pom.xml

<!-- alibaba sentinel -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- alibaba nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- alibaba nacos sentinel -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2 、l

server:
  port: 84
spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        # 默认8719端口,假如被占用会自动从8719开始一次+1稻苗,知道找到违背占用的端口
        port: 8719
# 消费者将要去访问的服务名称(注册进nacos的服务提供者名称)
service-url:
  nacos-user-service: http://nacos-payment-provider

3. The main startup class

@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}

4. Load balancing

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getLoadBalanced() {
        return new RestTemplate();
    }
}

5、controller

@Slf4j
@RestController
public class CirleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback")
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
        }
        return result;
    }
    public CommonResult<Payment> fallback(BlockException blockException) {
        return new CommonResult<Payment>(444, "", null);
    }
}

test

Start sequence nacos, sentinel, 9003, 9004, and finally start caller 84
1. @SentinelResource (value = "fallback", fallback = "handlerFallback")  fallback

@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback", fallback = "handlerFallback")//只负责业务异常
public CommonResult<Payment> fallback(@PathVariable Long id) {
    CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
    if (id == 4) {
        throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
    } else if (result.getData() == null) {
        throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
    }
    return result;
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
    Payment payment = new Payment(id, null);
    return new CommonResult(444, "兜底异常handlerFallback,exception内容" + e.getMessage(), payment);
}

Test result

2. Test @SentinelResource(value = "fallback", blockHandler = "handlerFallback") blockHandler. blockHandler is only responsible for the configuration of the sentinel console

@SentinelResource(value = "fallback", blockHandler = "blockHandler")//blockHandler只负责sentinel控制台的配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
    CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
    if (id == 4) {
        throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
    } else if (result.getData() == null) {
        throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
    }
    return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
    Payment payment=new Payment(id,null);
    return new CommonResult(445,"blockHandler-sentinel限流,无此流水,blockException:"+blockException.getMessage(),payment);
}

Test result (the first abnormal page, refreshed more than 2 times in one second, the sentinel current limit rule appears)

3. How to execute if both fallback and blockHandler are configured

@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallback = "handlerFallback", blockHandler = "blockHandler")
public CommonResult<Payment> fallback(@PathVariable Long id) {
    CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
    if (id == 4) {
        throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
    } else if (result.getData() == null) {
        throw new NullPointerException("NullPointerException,该id没有对应的记录,空指针异常");
    }
    return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
    Payment payment=new Payment(id,null);
    return new CommonResult(445,"blockHandler-sentinel限流,无此流水,blockException:"+blockException.getMessage(),payment);
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
    Payment payment = new Payment(id, null);
    return new CommonResult(444, "兜底异常handlerFallback,exception内容" + e.getMessage(), payment);
}

Results (Refresh the browser more than 2 times in 1 second)

If both blockHandler and fallback are configured, they will only enter the blockHandler processing logic when the current limit is degraded and BlockException is thrown.

exceptionsToIgnore

Fenign blow

Modify cloudalibaba-consumer-nacos-order84 to use feign call

1 、 pom.xml

<!-- openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2 、 aplication.yml

# 激活sentinel对feign的支持
feign:
  sentinel:
    enabled: true

3. Open support for feign@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain84 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}

4. OpenFeign provides an interface to call OpenClient


@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
public interface PaymentService {
    @GetMapping("/paymentSQL/{id}")
    public CommonResult paymentSQL(@PathVariable("id") Long id);
}
@Component
public class PaymentFallbackService implements PaymentService {
    @Override
    public CommonResult paymentSQL(Long id) {
        return new CommonResult<Payment>(4444,"",new Payment(id,"errorSerial"));
    }
}

test

Start nacos, sentinel, 9003, 9004, 84, visit the address

1.  http://localhost:84/consumer/paymentSQL/1 visit result (normal visit)
2. Turn off 9003 or 9004 at this time, and refresh the visit again as follows

You will find that the call fails, and the service is automatically degraded

Guess you like

Origin blog.csdn.net/www1056481167/article/details/113697484