1. 程式人生 > >SpringCloud(四):服務消費(Feign)

SpringCloud(四):服務消費(Feign)

一、Feign介紹 Feign是一個宣告式的偽Http客戶端,它使得寫Http客戶端變得更簡單。使用Feign,只需要建立一個介面並註解。它具有可插拔的註解特性,可使用Feign 註解和JAX-RS註解。Feign支援可插拔的編碼器和解碼器。Feign預設集成了Ribbon,並和Eureka結合,預設實現了負載均衡的效果。  

二、Feign消費者

pom.xml

        <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.cloud</groupId>             <artifactId>spring-cloud-starter-eureka-server</artifactId>         </dependency>         <dependency>             <groupId>org.springframework.cloud</groupId>             <artifactId>spring-cloud-starter-feign</artifactId>         </dependency> application.properties

spring.application.name=hello-consumer-feign server.port=8031

eureka.client.serviceUrl.defaultZone=http://localhost:8001/eureka/ Feign客戶端

package cn.saytime.service;

import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("hello-service") public interface HelloService {

    @RequestMapping("hello")     String hello (@RequestParam(value = "name") String name) ; } 注意點:這裡hello-service大小寫都可以,預設會轉成大寫

還有一點要注意:

@RequestParam(value = "name") 這裡必須是這樣配置,如果不配置或者配置的value=name1或者是其他值,相當於傳其他引數key過去,在這裡傳錯的話,會返回hello, null,因為hello-service介面拿不到name的值。  

啟動類

package cn.saytime;

import cn.saytime.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients @RestController public class HelloConsumerFeignApplication {

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

    @Autowired     private HelloService helloService;

    @RequestMapping("hello")     public String hello(String name){         return helloService.hello(name);     } } 三、測試 同樣的,先啟動eureka-server:8001, 以及hello-service:8011,8012,然後訪問:

http://localhost:8031/hello?name=feign

結果:

hello, feign 同樣的多次訪問,hello-service:8011,8012日誌都有列印呼叫資訊,表示也實現了負載均衡。