OpenFeign服务接口调用
声明式REST客户端:Feign创建一个用JAX-RS或Spring MVC注释修饰的接口的动态实现。
OpenFeign使用
- 消费端pom文件引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- yaml
eureka:
client:
register-with-eureka: false #feign是个客户端,不用注册
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
- 主启动类加
@EnableFeignClients
注解
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class FeignServerMain {
public static void main(String[] args) {
SpringApplication.run(FeignServerMain.class,args);
}
}
- 业务逻辑接口+
@FeignClient
注解
@Component
@FeignClient(value = "CLOUD-CLIENT") //value为调用的服务的程序名
public interface FeignService {
@GetMapping(value = "/payment/get/{id}") //此处为调用服务的url地址
public Result getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
public String TimeOut();
}
- controller
@Autowired
private FeignService feignService;
@GetMapping(value = "/feign/get/{id}")
public Result getPaymentById(@PathVariable("id") Long id){
Result result = feignService.getPaymentById(id);
log.info(result.toString());
return result;
}
@GetMapping(value = "/feign/timeout")
public String TimeOut(){
return feignService.TimeOut();
}
- 测试(OpenFeign自带负载均衡配置)
OpenFeign超时控制
OpenFeign默认等待一秒钟,超时就会报错
- 服务提供方设置3秒等待,服务消费方不做任何处理
@GetMapping(value = "/payment/feign/timeout")
public String TimeOut() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
-
测试
浏览器输入http://localhost/feign/timeout后一秒返回错误页面
-
超时等待时间设置(服务消费端设置)
# 设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
# 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
ReadTimeout: 5000
# 指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
- 测试 3秒后返回程序运行结果
OpenFeign日志打印
对接口调用情况进行监控和输出
共有四种日志级别:NONE,BASIC,HEADERS, FULL
- 新增配置类FeignConfig
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
- yaml配置
logging:
level:
# feign日志以什么级别监控哪个接口
com.cloud.service.FeignService: debug
- 测试
控制台打印相关日志