SpringCould-熔断

启动类增加注解 启用熔断机制。

package com.sxpcwlkj.order_server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker  //启用熔断机制
public class OrderServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServerApplication.class, args);
    }


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


}

创建类 ProductClientFallback

集成了 Feign 接口类

package com.sxpcwlkj.order_server.fallbcak;


import com.sxpcwlkj.order_server.service.ProductClient;
import org.springframework.stereotype.Component;

/**
 * 针对商品服务,错降级处理
 * 这里是集成了 Feign 接口类
 */
@Component
public class ProductClientFallback implements ProductClient {


    @Override
    public String selectByIdTwo(int id) {
        System.err.println("XXXXXXXXXXXXXXXXXXXXX");
        return "鸭梨山大...";
    }
}

管理配置注解

@FeignClient(name = “product-service”,fallback = ProductClientFallback.class)

package com.sxpcwlkj.order_server.service;


import com.sxpcwlkj.order_server.fallbcak.ProductClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 商品服务客户端
 */
@FeignClient(name = "product-service",fallback = ProductClientFallback.class)
//@FeignClient(name = "product-service")
public interface ProductClient {


    @GetMapping("/api/v1/product/selectByIdTwo")
    String selectByIdTwo(@RequestParam(value = "id") int id);



}

模拟:

商品服务抛异常

会走

System.err.println(“XXXXXXXXXXXXXXXXXXXXX”);

return “鸭梨山大…”;

posted @ 2021-07-16 15:06  烟燃烟灭  阅读(144)  评论(0编辑  收藏  举报