SpringCloud分佈式(三) 服務調用Feign

Feign

Feign是一個聲明式服務調用工具,使用它,我們只要定義接口即可,Feign會幫我們動態生成一個實現了這個接口的類,這個類進行請求的封裝,比直接用RestTemplate更簡單。
基本使用:
1、新建項目的時候選擇Feign或者在pom中新增(不同版本不一樣,建議用Starter來建)

org.springframework.cloud
spring-cloud-starter-openfeign

2、在**Application上標註@EnableFeignClients、@EnableDiscoveryClient
3、針對服務器端這個/calc/add接口:編寫接口

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

@FeignClient("restservice1")
public interface CalcService {
	
	@RequestMapping("/calc/add")
	public int add(@RequestParam("i") int i,@RequestParam("j") int j);
}

不能在接口上聲明@RequestMapping,在降級的時候好像會有坑
其中@FeignClient(“restservice1”)表示接口綁定restservice1這個服務。@RequestMapping("/calc/add")表示綁定服務器端哪個路徑。@RequestParam(“j”)表示參數來自於請求參數中的名字。

4、在使用的地方注入CalcService即可。

如果獲取報文頭中的參數信息就用@RequestHeader,如果獲取Json報文體,則使用@ReqeustBody。

Feign的服務降級
1、啓用hystrix,在application.properties中添加
feign.hystrix.enabled=true
2、編寫接口的實現類:

@Component
public class CalcServiceFallBack implements CalcService {

	@Override
	public int add(@RequestParam("i") int i,@RequestParam("j") int j) {
		return -1;
	}
}

然後修改CalcService接口的註解,變成:@FeignClient(name=“restservice1”,fallback=CalcServiceFallBack.class),也就是指定這個接口的降級類是CalcServiceFallBack

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章