定义api消费侧的接口,采用@FeignClient注解,会动态生成实现类。根据cloud-payment-service
的名称去eureka上找应用。
@Service
@FeignClient(value="cloud-payment-service")
public interface PaymentFeignService {
@GetMapping(value="/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
@GetMapping(value="/payment/feign/timeout")
public String paymentFeignTimeout();
}
调用方通过使用该声明的接口,就可以调用相关api。
@RestController
@RequestMapping(value="/consumer")
public class OrderFeignController {
@Autowired
private PaymentFeignService paymentFeignService;
@GetMapping(value="/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
@GetMapping(value="/payment/feign/timeout")
public String paymentFeignTimeout() {
return paymentFeignService.paymentFeignTimeout();
}
}
采用@EnableFeignClients注解,启用openfeign
@SpringBootApplication
@EnableFeignClients
public class CloudConsumerFeignOrder80 {
public static void main(String[] args) {
SpringApplication.run(CloudConsumerFeignOrder80.class, args);
}
}
配置文件如下
# 端口号80可以不带端口
server:
port: 80
# 声明应用名称
spring:
application:
name: cloud-consumer-order
# eureka注册中心地址,定义实例名称,选择ip的方式
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}
# openfeign 定义连接超时时间,以及logger日志级别
feign:
client:
config:
default:
connect-timeout: 5000
read-timeout: 5000
logger-level: basic
# 类的日志级别
logging:
level:
com.example.springcloud.service.PaymentFeignService: debug