spring-cloud-openFeign详解
1、引入OpenFeign依赖
<!--springcloud-openfeign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.5.RELEASE</version> </dependency>
2、定义FeignClict 接口
使用@FeignClient(name = 服务名,path = 服务下controller类上路径,configuration = feign配置)
package com.mj.feign.serive.nacos; import com.mj.feign.config.FeignConfig; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "api-nacos", path = "/nacos", configuration = FeignConfig.class) public interface NacosFeignService { @GetMapping("/get") String getUsername(); }
3、配置启动类
添加@EnableFeignClients 可以指定包名@EnableFeignClients({“com.mj.feign.*”})
@SpringBootApplication @EnableFeignClients public class JayNacosApplication { public static void main(String[] args) { SpringApplication.run(JayNacosApplication.class, args); } }
4、Feign配置类
package com.mj.feign.config; import com.mj.feign.intercept.CustomizeIntercept; import feign.Logger; import feign.Request; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * OpenFeign 配置类 还可以通过 配置文件配置 * 全局配置: 当使用@Configuration 会将配置作用所有的服务提供方 * 局部配置:1、 通过配置类 如果只针对某一个服务进行配置,就不要加@Configuration 在对应的Feign 接口加上 configuration = FeignConfig.class * 局部配置:2、 通过配置文件 feign: client: config: 服务名: loggerLevel: BASIC */ @Configuration public class FeignConfig { /** * Feign 请求日志配置 2、配置文件方式 feign: client: config: 服务名: loggerLevel: BASIC * * @return */ @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } /** * 超时时间配置 2、配置文件方式 feign: client: config: 服务名: readTimeout: 10000 connectTimeout: 5000 * @return */ @Bean public Request.Options options(){ // 连接超时时间 读取超时时间 return new Request.Options(5000,10000); } /** * 自定义拦截器配置 2、配置文件方式 feign: client: config: 服务名:requestInterceptor[0]: com.mj.feign.intercept.CustomizeIntercept */ @Bean public CustomizeIntercept customizeIntercept(){ return new CustomizeIntercept(); } }
下一篇:
设计模式--生成器模式