Sentinel整合RestTemplate和Feign案例

一、相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>com.zhq.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-consumer-nacos-order83</artifactId>

    <dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--SpringCloud alibaba sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--SpringCloud alibaba sentinel sentinel-datasource-nacos 持久化相关 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>
        <!--SpringCloud alibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zhq.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

二、相关配置

server:
  port: 83
spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        # 配置Nacos地址
        server-addr: localhost:8848
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会依次+1扫描,直到找到未被占用的端口
        port: 8719
#消费者将要去访问的微服务名称(注册成功进nacos的服务提供者)
service-url:
  nacos-payment-service: http://nacos-payment-provider
management:
  endpoints:
    web:
      exposure:
        include: '*'
# 激活sentinel对Feign的支持
feign:
  sentinel:
    enabled: true

三、案例代码

1)、启动类

/**
 * @author Mr.Zheng
 * @Program: cloud2020
 * @Description: 项目启动类
 * @date 2020-10-27 11:06
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain83 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain83.class,args);
    }
}

2)、整合RestTemplate

@Configuration
public class ApplicationContextConfig {

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

3)、整合Feign

@FeignClient(value = "nacos-payment-provider",fallback = PaymentServiceFeignImpl.class)
public interface PaymentServiceFeign {

    @GetMapping("/payment/nacos/{id}")
    CommonResult<Payment> getPayment(@PathVariable("id") Long id);
}
@Component
public class PaymentServiceFeignImpl implements PaymentServiceFeign {
    @Override
    public CommonResult<Payment> getPayment(Long id) {
        return new CommonResult<>(500,"服务降级返回");
    }
}

4)、测试代码

@RestController
@Slf4j
public class OrderNacosController {

    @Value("${service-url.nacos-payment-service}")
    private String serverURL;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentServiceFeign paymentServiceFeign;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id){
        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);
    }

    @GetMapping("/consumer/testFallback/{id}")
    @SentinelResource(value = "testFallback",fallback = "fallback",blockHandler = "handleException",exceptionsToIgnore = {NullPointerException.class})
    public CommonResult<Payment> testFallback(@PathVariable("id") Long id){
        if(id==4){
           throw  new  IllegalArgumentException("非法参数");
        }
        CommonResult<Payment>  result= restTemplate.getForObject(serverURL+"/payment/nacos/"+id,CommonResult.class,id);
        if(result.getData()==null){
            throw new NullPointerException("id没有记录");
        }
        return result;
    }

    public CommonResult fallback(@PathVariable("id") Long id,Throwable e){
        return new CommonResult(500,e.getClass().getCanonicalName()+"fallback管java异常,服务不可用");
    }

    public CommonResult handleException(@PathVariable("id") Long id,BlockException e){
        return new CommonResult(500,e.getClass().getCanonicalName()+"handleException管Sentinel规则异常,服务不可用");
    }

    @GetMapping("/consumer/testFeign/{id}")
    public CommonResult<Payment> testFeign(@PathVariable("id") Long id){
        return paymentServiceFeign.getPayment(id);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值