一、簡介web
Feign是一個聲明式的僞Http客戶端,它使得寫Http客戶端變得更簡單。使用Feign,只須要建立一個接口並註解。它具備可插拔的註解特性,可以使用Feign 註解和JAX-RS註解。Feign支持可插拔的編碼器和解碼器。Feign默認集成了Ribbon,並和Eureka結合,默認實現了負載均衡的效果。spring
簡而言之:apache
二、建立feign服務瀏覽器
二、1 建立springboot工程serice-feign,pom.xml以下:springboot
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lishun</groupId> <artifactId>serice-feign</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>serice-feign</name> <description>Demo project for Spring Boot</description> <parent> <groupId>com.lishun</groupId> <artifactId>cloud</artifactId> <version>1.0-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
2.二、配置文件application.yml,在配置文件中指定服務名,端口,註冊中心地址等信息app
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8765
spring:
application:
name: service-feign
2.三、在程序的啓動類ServiceFeignApplication ,加上@EnableFeignClients註解開啓Feign的功能:負載均衡
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class SericeFeignApplication { public static void main(String[] args) { SpringApplication.run(SericeFeignApplication.class, args); } }
2.四、定義一個feign接口,經過@ FeignClient(「服務名」),來指定調用哪一個服務。好比在代碼中調用了service-hi服務的「/hi」接口,代碼以下:maven
@FeignClient(value = "service-hi") public interface SchedualServiceHi { @RequestMapping(value = "/hi",method = RequestMethod.GET) String sayHiFromClientOne(@RequestParam(value = "name") String name); }
2.五、在Web層的controller層,對外暴露一個」/hi」的API接口,經過上面定義的Feign客戶端SchedualServiceHi 來消費服務。代碼以下:spring-boot
@RestController public class HiController { //編譯器報錯,無視。 由於這個Bean是在程序啓動的時候注入的,編譯器感知不到,因此報錯。 @SuppressWarnings("all") @Autowired SchedualServiceHi schedualServiceHi; @GetMapping(value = "/hi") public String sayHi(@RequestParam String name) { return schedualServiceHi.sayHiFromClientOne( name ); } }
2.六、啓動eureka-server ,端口爲8761; 啓動service-hi 兩次,端口分別爲8762 、8773.再啓動serice-feign 端口爲8765,屢次訪問http://localhost:8765/hi?name=lis,瀏覽器交替顯示:編碼
hi lis,i am from port:8762
hi lis,i am from port:8763