Feign是一個聲明式Web Service客戶端。使用Feign能讓編寫Web Service客戶端更加簡單, 它的使用方法是定義一個接口,然后在上面添加注解,同時也支持JAX-RS標准的注解。Feign也支持可拔插式的編碼器和解碼器。Spring Cloud對Feign進行了封裝,使其支持了Spring MVC標准注解和HttpMessageConverters。Feign可以與Eureka和Ribbon組合使用以支持負載均衡
本篇基於上一篇的項目
創建Feign服務
新建一個model,serice-feign工程,引入feign依賴spring-cloud-starter-openfeign
,eureka客戶端
依賴
pom文件如下
<!--Eureka依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--Web依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Feign依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
spring-cloud-starter-openfeign: 這個包是springcloud對於Feign的封裝,Feign是一個聲明式的Web服務客戶端。它支持Feign本身的注解、JAX-RS注解以及SpringMVC的注解。
編寫配置文件application.yml
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8765 spring: application: name: service-feign
在啟動類上加上@EnableFeignClients
注解
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class ServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(ServiceFeignApplication.class, args); } }
定義一個feign接口ServiceFeignTest接口,通過@ FeignClient(“服務名”),來指定調用哪個服務。比如在代碼中調用了service-client服務的“/test”接口,代碼如下:
@FeignClient(value = "eureka-client")//name:遠程服務名,此類中的方法和遠程服務中contoller中的方法名和參數需保持一致 public interface ServiceFeignTest { @RequestMapping(value = "/test", method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
創建controller層FeignTestController,來消費服務
@RestController public class FeignTestController { @Autowired ServiceFeignTest serviceFeignTest; @GetMapping(value = "/test") public String sayHi(@RequestParam String name) { return serviceFeignTest.sayHiFromClientOne(name); } }
依次啟動eureka-server,2個service-client,server-feign
多次訪問http://localhost:8764/hi?name=haha,會交替顯示
hi haha ,現在的端口是:8762 hi haha ,現在的端口是:8763