Feign
是一个声明式的web
服务客户端,让编写web
服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可。
GitHub
:https://github.com/spring-cloud/spring-cloud-openfeign
Feign在消费端使用
依赖:
包含了ribbon
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
配置文件:
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
主启动类:
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class,args);
}
}
定义业务逻辑接口:
业务逻辑接口+@FeignClient配置调用provider服务
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
控制层Controller:
@Slf4j
@RestController
public class OrderFeignController {
@Autowired
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id)
{
return paymentFeignService.getPaymentById(id);
}
}
测试:
先启动2个eureka集群7001/7002
再启动2个微服务8001/8002
启动服务消费者,OpenFeign启动。
http://localhost/consumer/payment/get/1
服务提供方8001,8002故意写暂停程序,模拟耗时长的业务:
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout(){
try { TimeUnit.SECONDS.sleep(3); }catch (Exception e) {e.printStackTrace();}
return serverPort;
}
服务消费方接口:
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeout();
}
服务消费方controller:
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
//openfeign-ribbon,客户端一般默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
测试:
直接访问服务提供者:http://localhost:8001/payment/feign/timeout
等待3秒后出结果
访问服务消费者接口:http://localhost/consumer/payment/feign/timeout
,直接报错了
OpenFeign
默认等待一秒钟,超过后报错
配置文件:
#设置feign客户端超时时间(openfeign默认支持ribbon)
ribbon:
#建立连接后,读取到可用资源所用的时间
ReadTimeout: 5000
#建立连接所用的时间
ConnectTimeout: 5000
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
配置文件:
服务消费方接口,打印debug日志
logging:
level:
com.lzh.springcloud.service.PaymentFeignService: debug