当前位置: 首页 > news >正文

广告文案优秀网站/公司软文推广

广告文案优秀网站,公司软文推广,附近网站建设公司,如何做自动网站Feign 深度解析 Feign 作为 Spring Cloud 生态中的声明式 HTTP 客户端,通过优雅的接口注解方式简化了服务间调用。本文将深入解析 Feign 的核心用法,并通过代码示例演示各种实战场景。 一、Feign 基础使用 1.1 环境搭建 添加 Maven 依赖(Sp…

Feign 深度解析

Feign 作为 Spring Cloud 生态中的声明式 HTTP 客户端,通过优雅的接口注解方式简化了服务间调用。本文将深入解析 Feign 的核心用法,并通过代码示例演示各种实战场景。

一、Feign 基础使用

1.1 环境搭建

添加 Maven 依赖(Spring Cloud 2021.0.1 版本):

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><version>3.1.0</version>
</dependency>
1.2 接口声明示例
@FeignClient(name = "user-service", url = "http://api.example.com")
public interface UserServiceClient {@GetMapping("/users/{id}")User getUserById(@PathVariable("id") Long userId);@PostMapping("/users")User createUser(@RequestBody User user);@GetMapping("/users/search")List<User> searchUsers(@RequestParam("name") String name,@RequestParam("age") int age);
}
1.3 启用 Feign
@SpringBootApplication
@EnableFeignClients
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}

二、高级配置详解

2.1 超时与重试配置

application.yml 配置示例

feign:client:config:default:connectTimeout: 5000readTimeout: 10000loggerLevel: fulluser-service:connectTimeout: 3000readTimeout: 5000retryer:maxAttempts: 3backoff: 1000
2.2 自定义配置类
@Configuration
public class FeignConfig {@Beanpublic Retryer retryer() {return new Retryer.Default(1000, 3000, 3);}@Beanpublic ErrorDecoder errorDecoder() {return new CustomErrorDecoder();}
}

三、异常处理机制

3.1 基础异常捕获
try {return userServiceClient.getUserById(userId);
} catch (FeignException e) {if (e.status() == 404) {throw new NotFoundException("User not found");}log.error("Feign call failed: {}", e.contentUTF8());throw new ServiceException("Remote service error");
}
3.2 自定义错误解码器
public class CustomErrorDecoder implements ErrorDecoder {@Overridepublic Exception decode(String methodKey, Response response) {if (response.status() >= 400) {String body = Util.toString(response.body().asReader());return new CustomException("API Error: " + response.status(),body);}return new Default().decode(methodKey, response);}
}

四、拦截器实战

4.1 认证拦截器
public class AuthInterceptor implements RequestInterceptor {@Overridepublic void apply(RequestTemplate template) {String token = SecurityContext.getCurrentToken();template.header("Authorization", "Bearer " + token);// 添加自定义追踪头template.header("X-Trace-Id", UUID.randomUUID().toString());}
}
4.2 日志拦截器
public class LoggingInterceptor implements RequestInterceptor {private static final Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);@Overridepublic void apply(RequestTemplate template) {log.debug("Request to {}: {}", template.url(), template.body());}
}

注册拦截器

@Configuration
public class FeignConfig {@Beanpublic AuthInterceptor authInterceptor() {return new AuthInterceptor();}
}

五、动态 URL 调用

5.1 直接指定 URL
@FeignClient(name = "dynamic-service", url = "${external.api.url}")
public interface ExternalServiceClient {@PostMapping("/process")Response processData(@RequestBody Payload payload);
}
/*** 请求拦截器动态改写目标地址*/
public class DynamicInterceptor implements RequestInterceptor {private final RoutingService routingService;@Overridepublic void apply(RequestTemplate template) {String target = routingService.resolve(template.feignTarget().name());template.target(target); // 根据策略引擎动态设置地址‌:ml-citation{ref="2,5" data="citationList"}}
}
5.2 RequestLine 方式
@FeignClient(name = "custom-client")
public interface CustomClient {@RequestLine("GET /v2/{resource}")String getResource(@Param("resource") String res, @Param("locale") String locale);
}

六、性能优化建议

  1. 连接池配置

    feign:httpclient:enabled: truemax-connections: 200max-connections-per-route: 50
    
  2. GZIP 压缩

    feign:compression:request:enabled: truemime-types: text/xml,application/xml,application/jsonresponse:enabled: true
    
  3. 缓存策略

    @Cacheable("users")
    @GetMapping("/users/{id}")
    User getUserById(@PathVariable("id") Long userId);
    

七、常见问题排查

7.1 405 Method Not Allowed

可能原因

  • 错误使用 GET 请求传递 Body
  • 路径参数未正确匹配

解决方案

// 错误示例
@GetMapping("/update")
void updateUser(@RequestBody User user); // GET 方法不能有请求体// 正确修改
@PostMapping("/update")
void updateUser(@RequestBody User user);
7.2 序列化异常

处理方案

@Bean
public Encoder feignEncoder() {return new JacksonEncoder(customObjectMapper());
}private ObjectMapper customObjectMapper() {return new ObjectMapper().registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}

八、最佳实践

  1. 接口隔离原则:每个 Feign 客户端对应一个微服务
  2. 版本控制:在路径中包含 API 版本号
    @FeignClient(name = "order-service", url = "${order.service.url}/v1")
    
  3. 熔断集成
    @FeignClient(name = "payment-service", fallback = PaymentFallback.class)
    public interface PaymentClient {// ...
    }
    

附录:常用配置参考表

配置项默认值说明
connectTimeout10s建立连接超时时间
readTimeout60s读取响应超时时间
loggerLevelNONE日志级别(BASIC, HEADERS, FULL)
retry.maxAttempts5最大重试次数
retry.backoff100ms重试间隔基数
http://www.whsansanxincailiao.cn/news/31976814.html

相关文章:

  • 大学两学一做专题网站/网络营销策划案例
  • 2023年疫情第三波爆发时间/seo外贸公司推广
  • 国外html5网站欣赏/谷歌paypal官网注册入口
  • 互联网怎么做网站/排名怎么优化快
  • 做网店装修的网站有哪些/网站制作流程图
  • 做网站规避什么/搜索引擎排名
  • 新冠肺炎疫情最新/佛山做优化的网络公司
  • 政府建设门户网站的意义/大数据智能营销
  • 赣州网站建设较好的公司/各类资源关键词
  • 做校招的网站有哪些/广州seo代理
  • js做示爱网站例子/长沙seo推广公司
  • 在线做免费网站有哪些/网站制作公司排名
  • 网站建设全程揭秘 课件下载/灰色项目推广渠道
  • 同江佳木斯网站建设/seo博客教程
  • php企业网站开发实训报告/seo免费教程
  • 两学一做专题网站介绍/湖南长沙seo
  • 配音阁在线制作网站/百度账号注册
  • 个人网站建设策划书/实体店引流推广方法
  • 高职思政主题网站建设作用/电商推广方案
  • 佛山网站建设灵格/自己可以创建网站吗
  • 做简历的网站有哪些/就在刚刚武汉宣布最新消息
  • 有pc网站 移动网站怎么做/市场营销推广活动方案
  • 国外二手表网站/广州谷歌推广
  • iis网站做文件下载按钮/100个商业经典案例
  • 做qq游戏的视频秀网站/友情链接网
  • 如何做网站子页/广告优化师工作内容
  • 做网站需要什么费用/seo搜索引擎优化期末考试
  • 贵州建设厅网站怎么查询资质/广州百度搜索排名优化
  • html编辑软件/百度seo点击排名优化
  • 开封网站网站建设/中国网站排名