一、Feign是一個(gè)聲明式的偽Http客戶端钱雷,它使得寫Http客戶端變的更為簡(jiǎn)單察藐。使用Fegin鸟雏,只需要?jiǎng)?chuàng)建一個(gè)接口并注解趁仙。它具有可插拔的注解特性,可使用Fegin注解和JAX-RS注解。Fegin支持可插拔的編碼器和解碼器。Fegin默認(rèn)集成了Ribbon什猖,并和Eureka結(jié)合,默認(rèn)實(shí)現(xiàn)了負(fù)載均衡的效果红淡。
簡(jiǎn)而言之:
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芯咧,端口號(hào)為8765,服務(wù)注冊(cè)地址為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層昧碉,對(duì)外暴露一個(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?