springCloud学习笔记系列(3)-服务容错保护:Spring Cloud Feign

Feign包含了Ribbon和Hystrix,这个在实战中才慢慢体会到它的意义,所谓的包含并非Feign的jar包包含有Ribbon和Hystrix的jar包这种物理上的包含,而是Feign的功能包含了其余二者的功能这种逻辑上的包含。简言之:Feign能干Ribbon和Hystrix的事情,可是要用Ribbon和Hystrix自带的注解必需要引入相应的jar包才能够。web

1.引入依赖spring

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->app

<dependency>maven

<groupId>org.springframework.cloud</groupId>ide

<artifactId>spring-cloud-starter-feign</artifactId>spring-boot

<version>1.4.6.RELEASE</version>url

</dependency>.net

2.配置文件中开启服务code

feign.hystrix.enabled=trueserver

3.启动类注解开启

@EnableFeignClients

public class DemoFeignApplication {

public static void main(String[] args) {

SpringApplication.run(DemoFeignApplication.class, args);

}

}

4.feign 是基于接口的注解方式实现的新建一个接口

@FeignClient(value = "two-client",fallback = SchedualServiceHiHystric.class)

public interface UserService {

@RequestMapping("/home/indexd")

String getIndex();

}

FeignClient("two-client"")注解里eureka-client指的是提供服务的服务名

fallback 自定义异常类

5.异常类的实现

@Component

public class SchedualServiceHiHystric implements UserService {

@Override

public String getIndex() {

return "服务没有开启";

}

}

 6.请求controller

@Autowired

private UserService userService;

 

@RequestMapping("/index")

public String index(){

logger.info("index方法");

return userService.getIndex();

}

7.结果,当调用的服务端没有开启的时候

注释:1.maven的依赖必定要匹配,否则版本不匹配就会报不少没法预知的异常(本人遇到很坑)

2.配置贴出来供参考

<dependencies>

<!--EuekaClient客户端依赖-->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka</artifactId>

<version>1.3.6.RELEASE</version>

</dependency>

<!--Web端依赖-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-feign</artifactId>

<version>1.3.6.RELEASE</version>

</dependency>

</dependencies>

#server.port=8013
#eureka.client.service-url.defaultZone=http://localhost:8000/eureka/
#spring.application.name=three-client
#feign.hystrix.enabled=true
server:
  port: 8013
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/
spring:
  application:
    name: three-client
feign:
  hystrix:
    enabled: true

hystrix:
  threadpool:
    default:
      coreSize: 500 #缺省为10
  stream:
    maxConcurrentConnections: 20
    bus:
      enabled: true
  command:
    default:
      execution:
        timeout:
          enabled: false
        isolation:
          thread:
            timeoutInMilliseconds: 60000
ribbon:
  eureka:
    enabled: true
相关文章
相关标签/搜索