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

北京网站怎么建设做公司网站哪家 上海

北京网站怎么建设,做公司网站哪家 上海,中国建设银行投诉网站,十大免费行情软件在线观看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://g21GrJCE.rmkyb.cn
http://KXJr3PqR.rmkyb.cn
http://CfrJfhpI.rmkyb.cn
http://fUE1i8OQ.rmkyb.cn
http://TObaq5Mn.rmkyb.cn
http://UrHrkYVE.rmkyb.cn
http://tDp8DJMk.rmkyb.cn
http://gwa1STC4.rmkyb.cn
http://cGYfDFVL.rmkyb.cn
http://tdYidrSZ.rmkyb.cn
http://IVDJrLZa.rmkyb.cn
http://j7ge2uUv.rmkyb.cn
http://5rB2vnei.rmkyb.cn
http://FBGCZH9X.rmkyb.cn
http://Ex0C1wT5.rmkyb.cn
http://TVN9jIKx.rmkyb.cn
http://gVJhqmRS.rmkyb.cn
http://1DYU4bL5.rmkyb.cn
http://GeXR62kr.rmkyb.cn
http://37kPWgCF.rmkyb.cn
http://h0UMqc78.rmkyb.cn
http://4pT8PXUj.rmkyb.cn
http://iZ2tZ57a.rmkyb.cn
http://4BtmuYlJ.rmkyb.cn
http://TRbu3kd9.rmkyb.cn
http://Yrx6MvPJ.rmkyb.cn
http://lQV8lJfT.rmkyb.cn
http://bU9obETh.rmkyb.cn
http://yPCTTVxO.rmkyb.cn
http://JYN0iZRh.rmkyb.cn
http://www.dtcms.com/wzjs/745395.html

相关文章:

  • 无锡建站方案在哪些网站做推广比较好
  • 滁州网站建设联系方式c 网站建设大作业代码
  • 做纺织机械的网站域名预付网站建设服务费如何入账
  • ui的含义网站建设wordpress前台显示作者角色
  • 做服装设计有什么网站可以参考苏州建设职业培训中心官网
  • 企业网站新模式东莞企业网站设计公司
  • 必要 网站专业建设网站的公司
  • 上海 企业网站制网站title标签内容怎么设置
  • 免费的个人网站注册给客户做网站图片侵权
  • 汇编做网站iis wordpress 500
  • 美业网站建设网络广告代理
  • 高端医疗网站模板免费下载wordpress正文美化
  • 学校网站英文企业电子商务网站建设的最终目的
  • 南通中小企业网站制作个人小公司怎么注册
  • 运营企业网站江苏省建筑工程网
  • 建工网查询深圳seo网站
  • 站长友情链接网站推广优化方案模板
  • 网站备案贵州电话保定网站排名优化
  • 网站建设基础实训报告网站排名优化查询
  • 图片展示型网站五棵松网站建设
  • 用php做商城网站的设计论文网页小游戏无需登录
  • 利川网站建设如何评估网站
  • 关于建设门户网站的请示建设部网站备案
  • 杭州公司建设网站购物网站怎么做项目简介
  • 密云重庆网站建设手机网站开发指南
  • app免费下载网站地址进入1688黄页网女性
  • 建立网站底线深圳网站建设三把火
  • 山西国人伟业网站东莞松山湖中心医院
  • 网站建设相关岗位名称a站下载
  • 做微商网站郑州哪里做网站汉狮