一、Feign是一個(gè)聲明式的偽Http客戶端,它使得寫Http客戶端變的更為簡單。使用Fegin,只需要?jiǎng)?chuàng)建一個(gè)接口并注解。它具有可插拔的注解特性,可使用Fegin注解和JAX-RS注解。Fegin支持可插拔的編碼器和解碼器。Fegin默認(rèn)集成了Ribbon,并和Eureka結(jié)合,默認(rèn)實(shí)現(xiàn)了負(fù)載均衡的效果。
簡而言之:
Fegin采用的是基于接口的注解
Fegin整合了ribbon
二、準(zhǔn)備工作
繼續(xù)用上一節(jié)的工程, 啟動(dòng)eureka-server,端口為8761; 啟動(dòng)service-hi 兩次,端口分別為8762 、8773.
三、創(chuàng)建一個(gè)feign的服務(wù)
新建一個(gè)spring-boot工程,取名為service-fegin,在它的pom文件引入Fegin的起步依賴spring-cloud-starter-feign、Eureka的起步依賴spring-cloud-start-eureka、Web的起步依賴spring-boot-starter-web,
在工程的配置文件application.yml文件,指定程序名為service-feign,端口號為8765,服務(wù)注冊地址為http://localhost:8761/eureka/?,代碼如下:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8765
spring:
application:
name: service-feign
在程序的啟動(dòng)類ServiceFeignApplication ,加上@EnableFeignClients注解開啟Feign的功能:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication{
?????public static void main(String[] args) {
? ? ? ? SpringApplication.run(ServiceFeignApplication.class, args);
? ? }
}
定義一個(gè)feign接口,通過@ FeignClient(“服務(wù)名”),來指定調(diào)用哪個(gè)服務(wù)。比如在代碼中調(diào)用了service-hi服務(wù)的“/hi”接口,代碼如下:
@FeignClient(value = "service-hi")
public interface SchedualServiceHi{?
?@RequestMapping(value = "/hi",method = RequestMethod.GET)
? ? String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
在Web層的controller層,對外暴露一個(gè)”/hi”的API接口,通過上面定義的Feign客戶端SchedualServiceHi 來消費(fèi)服務(wù)。代碼如下:
@RestController
public class HiController{
?????@Autowired SchedualServiceHi schedualServiceHi;
? ? @RequestMapping(value = "/hi",method = RequestMethod.GET)
? ? public String sayHi(@RequestParam String name){
? ? ? ? return schedualServiceHi.sayHiFromClientOne(name);
? ? }
}
啟動(dòng)程序,多次訪問http://localhost:8765/hi?name=forezp,瀏覽器交替顯示:
轉(zhuǎn)載:http://blog.csdn.net/forezp/article/details/69808079?