springcloud -sentinel 整合ribbon ,openfeign + fallback

发布时间 2023-07-10 23:17:48作者: 你就学个JVAV?

-------------------------|||||||    ribbon     |||||||-------------------------

//-----------------------------------------------------------------------------------------------------------provider 服务提供方

pom核心依赖


    <dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

yml  比较常规的配置

server:
  port: 9003

spring:
  application:
    name: nacos-payment-provider
  # nacos配置
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'

启动类注解不能少@EnableDiscoveryClient

测试地址http://localhost:9003/paymentSQL/1

//-----------------------------------------------------------------------------------------------------------consumer消费者端

 

core dependency

<!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--SpringCloud ailibaba sentinel  ( 需要使用sentinel对消费者侧进行熔断,降级,限流)-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

yml

server:
  port: 84


spring:
  application:
    name: nacos-order-consumer

  cloud:
    #nacos 配置
    nacos:
      discovery:
        server-addr: localhost:8848
    #sentinel配置
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719


#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider

 启动类注解@EnableDiscoveryClient 表示要注册中心发现

resttemplate bean

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

把fallback 和 blocHandler都配上  双剑合璧  服务更稳定

package com.atguigu.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@Slf4j
public class CircleBreakerController
{
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
     // value 资源id            fallback 运行时异常兜底方法名    blockHandler 自定义的降级兜底方法名
     @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,id);
        if (id == 4) {
            throw new IllegalArgumentException ("非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录");
        }
        return result;
    }
    
    // fallback handler
    public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(444,"fallback,无此流水,exception  "+e.getMessage(),payment);
    }
    
    // blockHandler
    public CommonResult blockHandler(@PathVariable  Long id,BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

}


 
若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。

 

-------------------------|||||||    openfeign + fallback (服务提供者宕机或者其他异常时,消费者将进入降级)    |||||||-------------------------

既然需要使用openfeign,就要导入openfeign的依赖

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

然后对yaml进行配置,添加下面的配置 ,激活sentinel对feign的支持

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

 接口类  服务降级关键注解  @FeignClient

// PaymentFallbackService为自定义降级处理类   value为服务提供者的名称
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)//调用中关闭9003服务提供者
public interface PaymentService
{    
    // 路径请与服务提供者的路径保持一致
    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}

 接口实现类

@Component
public class PaymentFallbackService implements PaymentService
{
    @Override
    public CommonResult<Payment> paymentSQL(Long id)
    {
        return new CommonResult<>(444,"服务降级返回,没有该流水信息",new Payment(id, "errorSerial......"));
    }
}

启动类

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients   // 启动类新增注解,启动对feign的支持
public class OrderNacosMain84
{
    public static void main(String[] args) {
            SpringApplication.run(OrderNacosMain84.class, args);
    }
}

此时即可输入http://localhost:84/consumer/paymentSQL/1(是你自己的地址) 进行测试