小編給大家分享一下Spring Cloud微服務(wù)之Feign怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
專業(yè)從事網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè),高端網(wǎng)站制作設(shè)計(jì),小程序制作,網(wǎng)站推廣的成都做網(wǎng)站的公司。優(yōu)秀技術(shù)團(tuán)隊(duì)竭力真誠(chéng)服務(wù),采用HTML5+CSS3前端渲染技術(shù),響應(yīng)式網(wǎng)站建設(shè),讓網(wǎng)站在手機(jī)、平板、PC、微信下都能呈現(xiàn)。建站過(guò)程建立專項(xiàng)小組,與您實(shí)時(shí)在線互動(dòng),隨時(shí)提供解決方案,暢聊想法和感受。
Feign是一個(gè)聲明式的http客服端,目標(biāo)是降低Http API的復(fù)雜性.可以用它來(lái)處理微服務(wù)間的調(diào)用.
01
—
接口模塊(demo-account)
1.AccountController
新增接口
@GetMapping("/{id}")public ResponseEntity> getById(@PathVariable("id") final long id) { final Account account = service.getById(id); log.info("getById:[{}]", account); return Rs.ok(account);}
02
—
Feign模塊(demo-feign)
1. 新建模塊demo-feign
,pom.xml
添加依賴
org.springframework.cloud spring-cloud-starter-openfeign
2. 新建AccountService
@FeignClient(name = "DEMO-ACCOUNT")public interface AccountService { @GetMapping("/demo-account/account/{id}") ResponseEntity> getById(@PathVariable("id") final long id);}
上面的getById方法可以直接復(fù)制對(duì)應(yīng)controller代碼,只保留用戶自定義參數(shù)即可,注意補(bǔ)全請(qǐng)求路徑.
@FeignClient的name為被調(diào)用服務(wù)注冊(cè)到注冊(cè)中心的名稱,即eureka.instance.appname,通常就是spring.application.name的值.
調(diào)用模塊(demo-feign)controller的請(qǐng)求方式要與被調(diào)用模塊(demo-account)保持一致.
3. 新建controller/AccountController
@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController {
@Resource
private AccountService service;
@GetMapping("/get-by-id")
@ApiOperation("通過(guò)id獲取賬戶詳情")
public ResponseEntity
> getById() { final ResponseEntity
> response = service.getById(1L); final Account account = Rs.requireNonNull(response, ResCode.ACCOUNT_FAIL_GET_BY_ID);
return Rs.ok(account);
}
}
4. 添加啟動(dòng)類 FeignApplication
@EnableFeignClients(basePackages = "io.github.ramerf.feign.service")@EnableDiscoveryClient@SpringBootApplication(scanBasePackages = {"io.github.ramerf.wind", "io.github.ramerf.feign"})public class FeignApplication { public static void main(String[] args) { SpringApplication.run(FeignApplication.class, args); }}
@EnableFeignClients的basePackages屬性,指定feign接口定義所在包.
03
—
啟動(dòng)模塊測(cè)試
啟動(dòng)demo-eureka
,demo-gateway
,demo-account
,demo-feign
模塊.
訪問(wèn): http://localhost:3000/demo-feign/account/get-by-id
以上是“Spring Cloud微服務(wù)之Feign怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!