SpringCloud分布式(三) 微服务调用Feign

Feign

Feign是一个声明式服务调用工具,使用它,我们只要定义接口即可,Feign会帮我们动态生成一个实现了这个接口的类,这个类进行请求的封装,比直接用RestTemplate更简单。
基本使用:
1、新建项目的时候选择Feign或者在pom中新增(不同版本不一样,建议用Starter来建)

org.springframework.cloud
spring-cloud-starter-openfeign

2、在**Application上标注@EnableFeignClients、@EnableDiscoveryClient
3、针对服务器端这个/calc/add接口:编写接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("restservice1")
public interface CalcService {
	
	@RequestMapping("/calc/add")
	public int add(@RequestParam("i") int i,@RequestParam("j") int j);
}

不能在接口上声明@RequestMapping,在降级的时候好像会有坑
其中@FeignClient(“restservice1”)表示接口绑定restservice1这个服务。@RequestMapping("/calc/add")表示绑定服务器端哪个路径。@RequestParam(“j”)表示参数来自于请求参数中的名字。

4、在使用的地方注入CalcService即可。

如果获取报文头中的参数信息就用@RequestHeader,如果获取Json报文体,则使用@ReqeustBody。

Feign的服务降级
1、启用hystrix,在application.properties中添加
feign.hystrix.enabled=true
2、编写接口的实现类:

@Component
public class CalcServiceFallBack implements CalcService {

	@Override
	public int add(@RequestParam("i") int i,@RequestParam("j") int j) {
		return -1;
	}
}

然后修改CalcService接口的注解,变成:@FeignClient(name=“restservice1”,fallback=CalcServiceFallBack.class),也就是指定这个接口的降级类是CalcServiceFallBack

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值