Spring Cloud第二章 服務消費者 Feign

上一篇文章,講述瞭如何通過eureka搭建服務註冊中心,這篇文章主要講述如何通過Feign去消費服務。:

一、feign

Feign是一個聲明式的僞Http客戶端,它使得寫Http客戶端變得更簡單。使用Feign,只需要創建一個接口並註解。它具有可插拔的註解特性,可使用Feign 註解和JAX-RS註解。Feign支持可插拔的編碼器和解碼器。Feign默認集成了Ribbon,並和Eureka結合,默認實現了負載均衡的效果。

簡而言之:

  • Feign 採用的是基於接口的註解
  • Feign 整合了ribbon,具有負載均衡的能力
  • 整合了Hystrix,具有熔斷的能力

二、啓動工程

先啓動eureka,在分別啓動兩個client

三、feign

引入feign依賴

	    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

在工程的配置文件application.yml文件,指定程序名爲service-feign,端口號爲8765,服務註冊地址爲http://localhost:8761/eureka/ ,代碼如下:

server:
  port: 8082
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

spring:
  thymeleaf:
    suffix: .html
  application:
    name: client2

在程序的啓動類 ,加上@EnableFeignClients註解開啓Feign的功能:

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

定義feign接口,並在接口使用註解@FeignClient(“服務名”),來指定調用哪個服務。比如在代碼中調用了client1服務的“/hello”接口,代碼如下:

@FeignClient("client1")
public interface IFeign {
    @RequestMapping("/hello")
    String hello();
}

在controller層,對外暴露一個"/hello"的API接口,通過上面定義的Feign客戶端IFeign 來消費服務。代碼如下:


@RestController
public class FeignConsumerController {
    @Autowired
    IFeign helloService;

    @RequestMapping("/hello")
    public String hello() {
        return helloService.hello();
    }
}

這樣一個簡單的服務之間調用就完成了,這裏在定義接口需要要注意這幾個註解@RequestParam,@RequestBody,@PathVariable基本沒甚了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章