openFeign代替Ribbon+RestTemlate

1.之前使用Ribbon+restTemplate完成服务调用,现在用openFeign代替,openFeign就是实现接口对接口的调用,简单来说就是接口+注解,不用写getForObject,getForEntity

openFeign与Ribbon一样,都是配置在客户端,openfeign也自带Ribbon。

2.pom:新增jar

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3.主启动开启Feign:

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
public class feignMain80 {
public static void main(String[] args) {
SpringApplication.run(feignMain80.class,args);
}
}

4.yml配置端口号和注册进服务中心。

server:
port: 80 #服务端口

eureka:
client:
# 表示将自己注册到eureka服务中心去
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

5.service层下接口+注解实现访问服务提供者的服务

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface paymentFeign {
//服务端的地址
@PostMapping("/payment/selectOne")
@ResponseBody
public ResultObject seleteOne(Integer id);
}

6.controller测试

@RequestMapping("/consumer/select")
@ResponseBody
public ResultObject order(int id){

return paymentFeign.seleteOne(id);
}

7.测试可以实现负载均衡和服务调用。

 

8.openFeign的超时控制,客户端的超时时间默认是1s,超过后会报错,现在修改为6s,yml文件添加,测试成功,注意timeout的超时时间是6s但是如果服务提供者sleep了6s还是会报错,因此配置的时间要大一些(仅供测试)


ribbon:

ReadTimeout: 6000

ConnectTimeout: 6000

9.配置openFeign的日志打印:

在主启动的同级目录建立config包及配置类,这里用FULL全日志打印

@Configuration
public class logopenFeign {
@Bean
public Logger.Level feignLoggerLevel() {
// 请求和响应的头信息,请求和响应的正文及元数据
return Logger.Level.FULL;
}
}

10.yml文件配置日志监控的接口

logging:
level:
# feign日志以什么级别监控哪个接口
com.cloud.openFeign.service.paymentFeign: debug

11.测试:

 

posted @ 2020-05-11 15:49  ~笑春风~  阅读(827)  评论(0)    收藏  举报