微服务互相调用-Feign

背景

实际开发中我们经常会面临在同一个eureka注册中心下的各个微服务之间互相调用彼此的接口来获取预期的数据。通过Spring Cloud Feign,我们只需要创建一个接口并用注解的方式来配置它,即可完成对服务提供方的接口绑定。

被调用服务及接口: hello-service服务的/hello接口。返回 hello world.
主微服务:feign-consumer

步骤

修改pom.xml

创建spring boot工程feign-comsumer,在pom.xml中引入spring-cloud-starter-eureka和spring-cloud-starter-feign

1
2
3
4
5
6
7
8
9
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-eureka</artifactId>
	<version>1.3.6.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

修改主类

修改应用主类ConsumerApplication,并通过@EnableFeignClients注解开启Spring Cloud Feign的支持功能。

1
2
3
4
5
6
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
	...
}

创建接口

定义HelloService接口,通过@FeignClient注解指定服务名来绑定服务,然后再使用Spring MVC的注解来绑定具体该服务提供的REST接口。

1
2
3
4
5
@FeignClient("hello-service")
public interface HelloService{
	@RequestMapping("/hello")
	String hello();
}

创建controller

接着创建一个controller来实现对Feign客户端的调用。使用@Autowired直接注入上面定义的HelloService实例,并在helloConsumer函数中调用这个便规定了hello-service服务接口的客户端来向该服务发起/hello接口调用。

1
2
3
4
5
6
7
8
9
10
@RestController
public class ConsumerController{
	@Autowired
	HelloService helloService;

	@RequestMapping(value="/feign-consumer",method=RequestMethod.GET)
	public String helloConsumer(){
		return helloService.hello();
	}
}

参数绑定

上面的例子中我们实现的是一个不带参数的REST服务绑定。然而现实系统中的各种业务接口要比它复杂的多,我们会在HTTP的各个位置传入各种不同类型的参数,并且在返回请求响应的时候也可能是一个复杂的对象结构。
修改接口声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@FeignClient("hello-service")
public interface HelloService{

	@RequestMapping("/hello")
	String hello();
	
	@RequestMapping(value="/hello1",method-RequestMethod.GET)
	String hello(@RequestParam("name") String name);

	@RequestMapping(value="/hello2",method-RequestMethod.GET)
	User hello(@RequestHeader("name") String name);

	@RequestMapping(value="/hello3",method-RequestMethod.GET)
	String hello(@RequestBody User user);
}

注意:在定义各参数绑定时,@RequestParam, @RequestHeader 等可以指定参数名称的注解,它们的value千万不能少。在springmvc程序中,这些注解会根据参数名来作为默认值,但是Feign中绑定参数必须通过value属性来指明具体的参数名,否则会抛出IllegalStateException异常,value属性不能为空

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

javafanwk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值