作用·:spring cloud提供了一个基础组件方便不同服务之间的HTTP调用,那就是openFeign openFeign默认是集成了Ribbon,默认实现了负载均衡
调用接口的代码流程只有两步:创建接口并且注解:
下面是对pom文件的分析:
<dependencies> <!--同时也是一个client端 需要对其引入pom-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--依赖openfeign pom文件申明-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--eureka集成了hystrix 所以必须对其进行引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
</dependencies>
下面是对application.yml文件的解读:
server:
port: 8090
spring:
application:
name: openFeign
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8082/eureka/
启动类的代码解读:
@SpringCloudApplication
@EnableFeignClients //标明这个注解,是表示这个模块是需要调用其他模块的接口的
@EnableHystrixDashboard //代表开启了dashboard界面查看熔断
public class ApplcationFeign {
public static void main(String[] args){
SpringApplication.run(ApplcationFeign.class, args);
}
具体代码的调用类:
@FeignClient(value = "eurekaclient", fallback = ApiServiceError.class) // 其中value属性是指属性那个application.name 名称
public interface ApiService {
@RequestMapping(value = "hello", method = RequestMethod.GET) //这里是对应了具体的接口路径,需要到原模块中去寻找
String test();
}
同时我们需要注意的一点就是它是集成了ribbon是可以负载均衡的
代码流程如下:
实现接口的class中的内容如下:
@Component
public class ApiServiceError implements ApiService {
@Override
public String test() {
return "服务器发生故障";
}
}
第二步就是:
@FeignClient(value = "eurekaclient", fallback = ApiServiceError.class) // 其中value属性是指属性那个application.name 名称,其中fallback属性就是出现异常情况之后需要返回
public interface ApiService {
@RequestMapping(value = "hello", method = RequestMethod.GET) //这里是对应了具体的接口路径,需要到原模块中去寻找
String test();
}
我们在知道了熔断器的使用之后,同时可以添加一个功能就是熔断器的监控功能
如下是对openFeign模块的pom文件改造:主要就是添加了两个pom包:
<!--需要使用到web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--使用dashboard界面查看熔断-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
然后在启动类上面需要添加注解:
@SpringCloudApplication
@EnableFeignClients //标明这个注解,是表示这个模块是需要调用其他模块的接口的
@EnableHystrixDashboard //代表开启了dashboard界面查看熔断
public class ApplcationFeign {
public static void main(String[] args){
SpringApplication.run(ApplcationFeign.class, args);
}
/**
* 将HystrixMetricsStreamServlet注入到spring容器中去,交给它管理
* @return
*/
@Bean
public ServletRegistrationBean getServlcet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet );
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
启动成功之后可以访问如下地址:http://localhost:8081/hystrix