小编给大家分享一下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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。