Feign已经断更,所以Spring官方也推荐使用OpenFeign。
这里就不浪费时间介绍什么是Feign了,自行百度!
使用方法:
一、 pom引入依懒
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
因为openFeign也整合了spring-cloud-starter-netflix-ribbon,所以它也带有负载均衡功能
二、yml配置文件中设置注册中心
根据自己的情况来,也可以使用单机版的注册中心测试。
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
三、主启动类使用@EnableFeignClients注解进行激活
@SpringBootApplication
@EnableFeignClients(basePackages = {"com.sany"})//basePackages扫描哪些包(一般设置全扫),也可以不写使用默认的
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class, args);
}
}
四、在service包(也可另起包 看自己)下新建的Feign接口,接口类上添加两个注解
@Component 必需要加,让spring扫描到
@FeignClient(value = "cloud-payment-service")其中的value是指被调用方(又叫暴露者;或者叫提供方)的服务名
@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
@GetMapping("/payment/get/{id}") //服务方提供的接口地址
CommonResult<Payment> getPayment(@PathVariable("id") Long id);
}
提供方的controller接口就不用我贴代码了吧!这里需要注意的是@GetMapping("/payment/get/{id}")这个接口地址要一致,不然就无法调用到;按住Ctrl + 鼠标左键能正常点过去就证明这个接口地址是对的。
服务降级
新建一个类实现PaymentFeignService 接口;@FeignClient上增加fallback 属性指定实现类。
PaymentFeignService 接口(正常情况下会走这个接口调用另一个微服务接口)
@Component
@FeignClient(value = "cloud-provider-hystrix-payment",
fallback = AaymentFallbackService.class)// AaymentFallbackService实现类
public interface PaymentFeignService {
@GetMapping("/payment/get/{id}") //服务方提供的接口地址
CommonResult<Payment> getPayment(@PathVariable("id") Long id);
}
AaymentFallbackService 实现类(异常情况下会走这个类中的方法返回自己定义的错误信息)
@Component
public class AaymentFallbackService implements PaymentFeignService {
@GetMapping("/payment/get/{id}") //服务方提供的接口地址
CommonResult<Payment> getPayment(@PathVariable("id") Long id){
return xxx;// 返回自定义错误信息
}
}
五、 在controller中申明后就可以在方法中进行调用了。
@Autowired
private PaymentFeignService feignService;
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return feignService.getPayment(id);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)