由于spingcloud  版本更新比较快,此处重新整理一版:

 

版本:  Java 8 

   spring boot  <version>  2.1.15.RELEASE </version>

   <spring-cloud.version>Greenwich.SR6</spring-cloud.version>

 

1. Feign的使用(配合Hystrix)

准备:在 service  MICRO-CLENT2-USER 写一个接口:

like:

 @RequestMapping(value = "/hello/{word}",method = RequestMethod.GET)
    public String hello(@PathVariable("word") String word){
        return feignService.hello(word);
    }

 

    @RequestMapping(value = "/order/queryOrderbyXXNoIn",method = RequestMethod.POST)
    public List<Order> queryOrderbyXXNoIn(@RequestParam(value = "xxName") String xxName ,@RequestParam(value = "xxNos",required = true) List<String> xxNos);

 文件下载。

    @GetMapping(value = "/booking/downloadOrderExcel",consumes = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
    com.feign.Response downloadOrderExcel (@RequestParam("s3key") String s3key);

 

    @PostMapping("/bagId/downLoadBagIdExcel")
    public void  genBagIdExcel (HttpServletResponse response, String status, MultipartFile multipartFile){
        try {
            Response responses = monitorClient.genBagIdExcel(status,multipartFile);
            InputStream inputStream = responses.body().asInputStream();
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + "result_BagIdData"+".xlsx");
            response.addHeader("Cache-Control", "no-cache");
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
        } catch (Exception e) {
            log.error("downloadBagIdExcel exception :{}",e);
        }

    }
View Code

 

 

 

文件上传:

    @RequestMapping(value = "/m/createOrUpdateWithExcel",method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<JSONObject> createOrUpdateMilestone(@RequestPart("excelFile") MultipartFile excelFile,
            @RequestParam("action") String  action,@RequestParam("userName") String  userName) ;

 

 

使用:

在service  MICRO-CLENT2-USER  中使用Feign 调用  MICRO-CLENT1-USER 的接口

 

依赖:

 

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

 

主类:

@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker 
@SpringBootApplication
public class EurekaServceApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServceApplication.class, args);
    }
}

 

配置文件:

server:
  port: 9002
spring:
  application:
    name: MICRO-CLENT2-USER
management:
  endpoint:
    health: #健康检测 查看 http://localhost:8761/actuator/health
      show-details: always
eureka:
  client:
    service-url:
      defaultZone: http://root:root@127.0.0.1:8761/eureka/
  instance:
   # 是否显示ip,如果不设置那么就会显示主机名,默认false
    prefer-ip-address: true
feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 7000
        readTimeout: 700

 

 

定义Feign调用接口:

/**
 @param: name :被调用服务的服务名
 @param: configuration :Feign的配置,可以不配,建议配置,解决连接超时,retry
 @param: fallback :Feign 默认支持hystrix, 自定义一个类,然后实现方法即可,如果链路失败,自调用备胎,返回默认值(做异常提示)
 */
@FeignClient(name = "MICRO-CLENT1-USER",configuration = FeignConfig.class,fallback = FeignServiceHystrxFall.class)
public interface FeignService {

         @RequestMapping(value = "/hello/{word}",method = RequestMethod.GET)
        public String hello(@PathVariable("word") String word);
    
}

 

定义Feign 的Config

@Configuration
public class FeignConfig {

      @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
        
        @Bean
        public Retryer feignRetryer(){
            return new Retryer.Default(100,TimeUnit.SECONDS.toMillis(1),5);
        }
        
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
        
        @Bean
        public Request.Options options() {
            return new Request.Options(60000, 60000);}
    
}

 

 

 

@Component
public class FeignServiceHystrxFall implements FeignService{
    @Override
    public String hello(String word) {
        //调用服务异常,断路
        //dosomething();
        return "上游服务异常";
    }
}

 

 

关于hystrix 的相关配置:

hystrix:
  # === === === == 默认Command === === === ==
  command:
    default:
      execution:
        isolation:
          # 调用隔离方式, 默认: 采用线程隔离, ExecutionIsolationStrategy:THREAD
          strategy: THREAD
          # 调用超时时间, 默认: 5 秒
          thread:
            timeoutInMilliseconds: 8000
          # 使用信号量隔离时, 命令调用最大的并发数
          semaphore:
            maxConcurrentRequests: 10
      #使用信号量隔离时, 命令fallback调用最大的并发数
      fallback:
        isolation:
          semaphore:
            maxConcurrentRequests: 10
      # === === === == 熔断器 === === === ==
      circuitBreaker:
        # 熔断器在整个统计时间内是否开启的阀值, 默认20个请求
        requestVolumeThreshold: 8
        # 熔断器默认工作时间, 默认: 5 秒
        sleepWindowInMilliseconds: 5
        # 默认: 50%, 当出错率超过50% 后熔断器启动
        errorThresholdPercentage: 50
        # 是否强制开启熔断器阻断所有请求, 默认: false, 不开启
        forceOpen: false
        # 是否允许熔断器忽略错误, 默认false, 不开启
        forceClosed: false

 

posted on 2020-06-19 19:03  lshan  阅读(344)  评论(0编辑  收藏  举报