温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Cloud微服务之Feign怎么用

发布时间:2021-12-24 10:36:08 来源:亿速云 阅读:138 作者:小新 栏目:大数据

小编给大家分享一下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);}
  1. 上面的getById方法可以直接复制对应controller代码,只保留用户自定义参数即可,注意补全请求路径.

  2. @FeignClient的name为被调用服务注册到注册中心的名称,即eureka.instance.appname,通常就是spring.application.name的值.

  3. 调用模块(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怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI