您好,登錄后才能下訂單哦!
小編給大家分享一下Spring Cloud微服務之Feign怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Feign是一個聲明式的http客服端,目標是降低Http API的復雜性.可以用它來處理微服務間的調用.
01
—
接口模塊(demo-account)
1.AccountController
新增接口
@GetMapping("/{id}")public ResponseEntity<Rs<String>> 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
添加依賴
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
2. 新建AccountService
@FeignClient(name = "DEMO-ACCOUNT")public interface AccountService { @GetMapping("/demo-account/account/{id}") ResponseEntity<Rs<Account>> getById(@PathVariable("id") final long id);}
上面的getById方法可以直接復制對應controller代碼,只保留用戶自定義參數即可,注意補全請求路徑.
@FeignClient的name為被調用服務注冊到注冊中心的名稱,即eureka.instance.appname,通常就是spring.application.name的值.
調用模塊(demo-feign)controller的請求方式要與被調用模塊(demo-account)保持一致.
3. 新建controller/AccountController
@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController {
@Resource
private AccountService service;
@GetMapping("/get-by-id")
@ApiOperation("通過id獲取賬戶詳情")
public ResponseEntity<Rs<String>> getById() {
final ResponseEntity<Rs<Account>> response = service.getById(1L);
final Account account = Rs.requireNonNull(response, ResCode.ACCOUNT_FAIL_GET_BY_ID);
return Rs.ok(account);
}
}
4. 添加啟動類 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
—
啟動模塊測試
啟動demo-eureka
,demo-gateway
,demo-account
,demo-feign
模塊.
訪問: http://localhost:3000/demo-feign/account/get-by-id
以上是“Spring Cloud微服務之Feign怎么用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。