Spring Cloud Feign入门

Spring Cloud Feign基于Netflix Feign,整合了Spring Cloud Ribbon和Spring Cloud Hystrix,还提供了一种声明式的Web服务客户端定义方式,也支持SpringMVC注解。同时Feign的一些主要主件是可插拔的,可以使我们很方便的扩展和替换。

一、基础项目搭建:

(1)pom. 文件需要添加spring-boot-starter-web、spring-cloud-starter-netflix-eureka-server和spring-cloud-starter-openfeign;
(2)启动类添加注解:

@EnableFeignClients //开启Spring Cloud Feign
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {

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

}

(3)定义service接口:

注意:服务名千万不要用下划线!使用下划线将导致服务无法被识别。

@FeignClient(name = \"service-curly-umbrella\") //(1)指定服务为名绑定服务(服务为名不区分大小写)
public interface TestService {

    @RequestMapping(\"/test/test04\") //(2)再使用springMVC注解绑定该服务提供的REST接口
    String test01();

}

(4)创建controller:

@RestController
@RequestMapping(\"/feign\")
public class TestController {

    @Resource
    private TestService testService;

    @RequestMapping(value = \"test01\",
                    method = RequestMethod.GET)
    public String test01(){
        return testService.test01();
    }

}

(5)application设置:

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

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

(6)测试:
\"在这里插入图片描述\"
输入“ http://localhost:9111/feign/test01 ”,观察返回结果;多次请求,观察服务提供者控制台,可以发现feign通过轮询实现了客户端的负载均衡。

收藏 打印