随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

由于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   lshan  阅读(347)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-06-19 mongoDB 笔记 https://www.runoob.com/mongodb/mongodb-query.html
点击右上角即可分享
微信分享提示