feign实现服务降级实现

feign集成了ribbon,但无法直接使用@HystrixCommand注解指定服务降级,现在来看看ribbon中如何实现服务降级逻辑

1.继承调用微服务的service接口,重写该接口中的服务调用方法实现降级逻辑

package com.cfh.eurekaconsumer.service.fallback;

import com.cfh.eurekaconsumer.service.HelloService;
import org.springframework.stereotype.Component;

//定义hello-service的降级逻辑
@Component
public class HelloServiceFallBack implements HelloService {
    @Override
    public String hello() {
        return "error";
    }
}

2.在服务调用类的@FeignClient接口中的fallback属性指定降级逻辑处理类

package com.cfh.eurekaconsumer.service;

import com.cfh.eurekaconsumer.service.fallback.HelloServiceFallBack;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(value = "hello-service",fallback = HelloServiceFallBack.class)
@Service
public interface HelloService {

    @RequestMapping("/hello")
    public String hello();
}

这样当调用hello-service服务的hello接口时,如果发生了熔断,将会触发服务降级,调用HelloServiceFallBack中指定的降级逻辑,返回error。

猜你喜欢

转载自blog.csdn.net/m0_37556444/article/details/82562314