版权声明:本博客所有的原创文章,转载请注明出处,作者皆保留版权。 https://blog.csdn.net/anLA_/article/details/80672780
Feign是什么呢?声明式服务调用,记得在使用Ribbon负载均衡时候,需要用到一个RestTemplate来进行调用,而有了Feign,可以直接写类似于Controller的方式来进行一个声明式的服务调用了。
Feign
Feign基于Netflix Feign实现,整合了Spring Cloud Ribbon与Spring Cloud Hystrix,除了提供这两者的强大功能外,它还提供了一种声明式的Web服务客户端定义方式。
下面看一个例子。
pom文件
首先是pom文件,引入eureka和feign即可:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
FeignClient的接口
Feign里面声明式的调用,通过在接口上用注解配置,如果失败了,则会调用fallback指定的类的同名方法,一般是实现一个子类进行容错。
下面看FeignService类:
@FeignClient(name="hello-service",fallback = FeignServiceFallback.class)
//此处name为eureka中注册实例名,feign会默认基于ribbon的负载均衡
public interface FeignService {
@RequestMapping("/hello")
public String hello();
}
下面再看FeignServiceFallback:
@Component
public class FeignServiceFallback implements FeignService {
@Override
public String hello() {
return "hello error";
}
}
启动类
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignApplication {
public static void main(String[] args){
SpringApplication.run(FeignApplication.class,args);
}
}
在启动类上,加上@EnableFeignClients
开启Feign服务。
application.yml
server:
port: 8082 #端口
spring:
application:
name: feign-service #为服务命名
feign:
hystrix:
enabled: true #一定要手动配置hystrix,默认feign是不开启hystrix服务的
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
注意一定要手动将feign.hystrix.enabled设为true,否则关闭hello-service时候,将不会触发容错。
当启动eureka,hello-service,feign应用时,访问http://localhost:8082/feign-consumer
而此时关闭hello-service,则会得到如下访问结果:
当然上面,只是简单搭建了一个Feign环境,对于声明式服务调用对应与http访问配置参数,继承等。
同时,可以在application.yml中配置相应的ribbon配置。
代码在hello-springcloud 的v4分支
扫描二维码关注公众号,回复:
3285098 查看本文章