SpringCloud Feign服务的消费者,如何相互调用
2019-02-14 12:36
465 查看
SpringCloud Feign服务于服务之间的相互调用
Feign
Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。
下面,通过一个例子来展现Feign如何方便的对服务实现调用的。
如图,已有的几个项目包:
现在授权服务auth-server里面创建一个测试的demo
代码如下
@RestController @RequestMapping(value = "/testFeign") public class TestController { @GetMapping(value = "/hello") public String hello(@RequestParam("name")String name) { return "hello " + name; } @PostMapping(value = "/hello1") public String hello1(@RequestBody MyUser user) { if (user == null) { return "未知"; } return user.toString(); } }
然后是消费这几个接口的eureka-client-demo1.首先是maven引用。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
接着开启feign注解
@EnableFeignClients。
@SpringCloudApplication @EnableFeignClients public class EurekaClientDemo1Application { public static void main(String[] args) { SpringApplication.run(EurekaClientDemo1Application.class, args); } }
接着去定义auth-server服务的接口
@FeignClient(value = "oauthServer") public interface HelloApiService { @GetMapping(value = "/testFeign/hello") public String hello(@RequestParam("name") String name); @PostMapping(value = "/testFeign/hello1") public String hello1(@RequestBody MyUser user); }
然后就可以愉快的使用啦。使用起来跟其他bean没有什么两样。
@Autowired private HelloApiService helloApiService; @RequestMapping("aa/feign") public Map<String,Object> hello1(){ Map<String,Object> ret = new HashMap<String, Object>(); StringBuffer sb = new StringBuffer(); String s1 = helloApiService.hello("张三"); sb.append(s1).append("\n"); String s3 = helloApiService.hello1(new MyUser("王五", "19")); sb.append(s3).append("\n"); ret.put("show",sb.toString()); return ret; }
测试结果如图:
已经成功的调用了auth-server的接口了,后面再加熔断和链路追踪。
相关文章推荐
- 使用Spring Cloud Feign作为HTTP客户端调用远程HTTP服务
- 非SpringCloud如何调用SpringCloud服务
- springcloud使用feign实现服务间条用,参数数据太大,无法调用成功解决方法
- 白话SpringCloud | 第四章:服务消费者(RestTemple+Ribbon+Feign)
- SpringCloud微服务知识整理六:声明式服务调用 Spring Cloud Feign
- 使用Spring Cloud Feign进行服务调用
- springcloud 服务feign调用问题
- 笔记:Spring Cloud Feign 声明式服务调用
- 使用Spring Cloud Feign作为HTTP客户端调用远程HTTP服务
- Spring Cloud(四)服务提供者 Eureka + 服务消费者 Feign
- 十一、Spring cloud服务调用(Feign)
- Spring Cloud中声明式服务调用Feign
- SpringCloud教程 | 第三篇: 服务消费者(Feign)
- Spring Cloud 声明式服务调用 Feign
- Springcloud微服务调用ribbon与feign
- Spring Cloud(服务的消费者 Feign)
- 使用Spring cloud Feign在后台服务之间调用传递Multipart无法传递的问题
- 关于Dalston.SR3版本的spring cloud,用feign客户端调用服务hystrix不能生效的问题
- SpringCloud--服务消费者(Feign)
- SpringCloud服务相互调用RestTemplate