OpenFeign使用时需要80端口自己写一个Service来调用8001端口的controller。
首先是添加依赖
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
然后yml和普通的80端口无区别,不需要修改,需要的话可以添加时间设置。
ribbon:
ReadTimeout: 5000 #建立连接后从服务器读取到可用资源所用时间
ConnectTimeout: 5000 #设置建立连接的等待时间
接着,主启动类加上注解
@EnableFeignClients
service层如下
@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
@GetMapping("/payment/getPaymentById/{id}")
CommonResult getPaymentById(@PathVariable("id") Long id);
}
FeignClient注解的value是8001端口的服务名称,getMapping后的访问地址和8001的controller相同,这样申明后就可以调用8001端口了
最后添加80端口自己的controller
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/getPaymentById/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
}
之后就可以在浏览器访问80端口进行测试了。
还可以开启feign的日志打印功能。
先添加配置类
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
注意,这里Logger导入的包是
扫描二维码关注公众号,回复:
12437957 查看本文章
import feign.Logger;
不要点错了。
接着添加yml配置
logging:
level:
#feign以什么级别监控哪个接口
com.meng.service.PaymentFeignService: debug
ok.