Spring Cloud Feign

156 阅读2分钟

工作这几年写了很多接口,主要都是Http接口,这些接口还都挺普通的,如果要说有一些不普通的那可能sdk中封装的接口有些不一样,但是当见到Sping Cloud Feign他定义的接口那才是真的不一样。

下面就来说一说Sping Cloud Feign

优点

1 模板化的Http接口,声明式接口就像调用一个方法一样简单

2 集成负载均衡,熔断服务降级

针对这两点分别进行阐述

为什么说他是声明式的接口,看代码,首先我们建立一个hello-service提供接口方法的服务,并将服务注册到Eruka上

@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class HelloApplication {

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

}

看一下这个服务中的接口方法

    @RestController
    public class HelloController {

        private final Logger logger = Logger.getLogger(getClass());

        @Autowired
        private DiscoveryClient client;

        @RequestMapping(value = "/hello", method = RequestMethod.GET)
        public String hello() throws Exception {
                ServiceInstance instance = client.getLocalServiceInstance();

                logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
                return "Hello World";
        }


 

我们看到/hello方法,这时候我们启动feign-consumer项目

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
            SpringApplication.run(ConsumerApplication.class, args);
    }

}

配置

spring.application.name=feign-consumer
server.port=9001

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/


然后我们开始写调用hello-server服务中/hello的方法,这时候就使用feign了

@FeignClient(name="HELLO-SERVICE", fallback = HelloServiceFallback.class)
public interface HelloService {

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

   

}

@FeignClient(name="HELLO-SERVICE"),这个就是指定要调用方法所在的服务

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

调用所在服务的/hello方法了,这种调用方式是不是很不一样

然后我们在写一个调用类测试一下 @RestController public class ConsumerController {

    @Autowired
    HelloService helloService;
    @Autowired
    RefactorHelloService refactorHelloService;

    @RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
    public String helloConsumer() {
        return helloService.hello();
    }
    

这时候访问feign服务 http://localhost:9001/feign-consumer

返回

image.png

这样通过feign的调用就完成了

针对第二点,负载均衡和熔断其实在zuul的讲说中已经提到了,feign的配置也是一致的,就不多说了。

下面说一说服务的降级fallback

 @FeignClient(name="HELLO-SERVICE", fallback = HelloServiceFallback.class)

这个是之前类的注解,这个注解指定了降级处理类HelloServiceFallback.class,他是这样的

@Component
public class HelloServiceFallback implements HelloService {

    @Override
    public String hello() {
        return "error";
    }

当触发熔断的时候,就会走降级的方法,返回error。 另外要注意的是,ribbon负载均衡,和Hystrix熔断都会设定时间,一个是超时时间一个是熔断时间,超时时间必须小于熔断时间,否则ribbon是不是进行重试的