1. 程式人生 > 其它 >springcloud整合feign

springcloud整合feign

1.新增依賴

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

2.在消費端新增代理

//DepartFeignFallBackFactory 服務降級使用
@FeignClient(value = "provider-test",fallbackFactory = DepartFeignFallBackFactory.class)
@RequestMapping("/provider/depart")
public interface DepartFeign {
    @PostMapping("/save")
    public boolean saveHandler(@RequestBody Depart depart);

    @DeleteMapping("/del/{id}")
    public boolean delHandler(@PathVariable("id") Integer id);

    @PutMapping("/update")
    public boolean updateHandler(@RequestBody Depart depart);

    @GetMapping("/get/{id}")
    public Depart getHandler(@PathVariable("id") Integer id);

    @GetMapping("/list")
    public List<Depart> listHandler();
}

 3.服務降級處理類

@Component
public class DepartFeignFallBackFactory implements FallbackFactory<DepartFeign> {
    @Override
    public DepartFeign create(Throwable throwable) {
        return new DepartFeign() {
            @Override
            public boolean saveHandler(Depart depart) {
                System.out.println("執行saveHandler降級的方法");
                return false;
            }

            @Override
            public boolean delHandler(Integer id) {
                System.out.println("執行delHandler降級的方法");
                return false;
            }

            @Override
            public boolean updateHandler(Depart depart) {
                System.out.println("執行updateHandler降級的方法");
                return false;
            }

            @Override
            public Depart getHandler(Integer id) {
                System.out.println("執行getHandler降級的方法");
                return null;
            }

            @Override
            public List<Depart> listHandler() {
                System.out.println("執行listHandler降級的方法");
                return null;
            }
        };
    }
}

  4.配置檔案

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
  hystrix:
    enabled: true
  circuitbreaker:
    enabled: true

provider-test:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #負載均衡策略