Spring Cloud Feign简单使用详解
概述
在SpringCloudEureKaRibbon服务注册-发现-调用一文中简单的介绍了在SpringCloud中如何使用EureKa和Ribbon。文章中使用了RestTemplate去访问其他的restful微服务接口。其实在SpringCloud还可以使用Feign来访问其他的restful微服务接口。使用起来更加的简洁明了。
集成Feign
修改一下SpringCloudEureKaRibbon服务注册-发现-调用中orderservice的pom配置,把Fegin引入进来即可。
org.springframework.cloud spring-cloud-starter-feign
修改OrderApplication类,删除如下代码:
@Bean @LoadBalanced RestTemplaterestTemplate(){ returnnewRestTemplate(); }
并加上@EnableFeignClients注解。完整代码如下:
packagecom.springboot; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.cloud.client.discovery.EnableDiscoveryClient; importorg.springframework.cloud.netflix.feign.EnableFeignClients; @EnableDiscoveryClient @EnableFeignClients @SpringBootApplication publicclassOrderApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(OrderApplication.class,args); } }
新增接口UserService,并使用@FeignClient注解。
packagecom.springboot; importorg.springframework.cloud.netflix.feign.FeignClient; importorg.springframework.web.bind.annotation.GetMapping; @FeignClient(name="user") publicinterfaceUserService{ @GetMapping(value="/getUser") StringgetUser(); }
这里的@FeignClient(name="user")中的name=user表示要访问user这个微服务。由于order这个微服务已经集成了Eureka和Ribbon。那么使用@FeignClient(name="user")访问user微服务的时候,已经自动支持客户端路由了。并且会从注册中心中找到user这个微服务。
修改OrderController,注入UserService。
packagecom.springboot; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.RestController; @RestController publicclassOrderController{ @Autowired privateUserServiceuserService; @GetMapping("/getOrderUser") publicStringgetOrderUser(){ returnuserService.getUser(); } }
这样就无需使用
restTemplate.getForEntity("http://user/getUser",String.class).getBody();
来调用user服务中的getUser接口了。而是直接使用userService.getUser()就可以了。
启动注册中心以及user和order这两个微服务。使用http://localhost:8883/getOrderUser
访问一下。是可以返回
Iamuserlist.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。