Spring Cloud远程调用之OpenFeign
发布时间:2026/10/22 6:49:03 锦皓数字建站

Feign是一个声明式的伪RPCFeign英文意思为“假装伪装变形”的REST客户端它用了基于接口的注解方式可以以Java接口注解的方式调用Http请求从而将请求模块化。Feign被广泛应用在Spring Cloud的解决方案中是学习基于Spring Cloud微服务架构不可或缺的重要组件。使用1、添加依赖dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-openfeign/artifactId/dependency2、启动类添加EnableFeignClients注解3、定义注解接口FeignClient注解里面的user-server为调用服务名packagedemo.newsweb.controller;importorg.springframework.cloud.openfeign.FeignClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;FeignClient(user-server)publicinterfaceUserControllerFeign{GetMapping(/user/login)Stringlogin(RequestParam(user)Stringuser,RequestParam(pwd)Stringpwd);}4、使用注解接口远程调用packagedemo.newsweb.controller;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;RestControllerRequestMapping(user)publicclassUserController{AutowiredprivateUserControllerFeignuserControllerFeign;GetMapping(/login)publicStringlogin(Stringuser,Stringpwd){returnuserControllerFeign.login(user,pwd);}}特性开启Gzip压缩# 请求开启压缩 feign.compression.request.enabledtrue # 最小压缩大小字符低于这个值则不压缩 feign.compression.request.min-request-size2048 # 响应开启压缩 feign.compression.response.enabledtrue # 压缩类型 text/xml, application/xml, application/json feign.compression.request.mime-typestext/xml,application/xml,application/jsonFeign日志配置1、配置日志输出级别# 日志级别 logging.level.[demo.newsweb.controller.UserControllerFeign]debug2、配置日志输出方式FULL为输出全部信息。packagedemo.newsweb.controller;importfeign.Logger;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;ConfigurationpublicclassFeginLogConfig{BeanLogger.LevelfeignLogger(){returnLogger.Level.FULL;}}3、Feign接口注解FeignClient加入configuration FeginLogConfig.class使用设置的日志输出方式packagedemo.newsweb.controller;importorg.springframework.cloud.openfeign.FeignClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;FeignClient(valueuser-server,configurationFeginLogConfig.class)publicinterfaceUserControllerFeign{GetMapping(/user/login)Stringlogin(RequestParam(user)Stringuser,RequestParam(pwd)Stringpwd);}输出信息如下替换默认的底层通信底层通信默认是URLConnection可替换成性能更好的okHttp添加依赖dependencygroupIdio.github.openfeign/groupIdartifactIdfeign-okhttp/artifactId/dependency添加配置启用feign.httpclient.enabledfalse feign.okhttp.enabledtrue
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。