Feign 自带ribbon
1: 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--<!–eureka-client 2.x版本使用,和之前不同,后缀已经表明了一切–>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2: application
server:
port: 8081
spring:
application:
name: cloud-order-service
eureka:
instance:
hostname: localhost
port: 7001
client:
register-with-eureka: false #false表示不向注册中心注册自己。
#是否从eurekaServer抓取自己的注册信息,默认是true。
#单节点无所谓,集群必须设置为true擦能配个ribbon使用负载均衡
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
logging:
level:
# feign日志以什么级别监控哪个接口
com.atguigu.springcloud.service.FeignPaymentService: debug
2: main 注册允许feign
@SpringBootApplication
@EnableFeignClients
//@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class FeignOrderMain80 {
public static void main(String[] args) {
SpringApplication.run(FeignOrderMain80.class,args);
}
}
3: FeignPaymentService 写接口,指向服务提供者的接口
1):CLOUD-PAYMENT-SERVICE 是服务提供者注册的名字,可在eureka上查看
2):payment/get/{id} , payment/openfeign/timeout 指向服务提供者里面congtroller的接口地址
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface FeignPaymentService {
@GetMapping("payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id")Long id);
@GetMapping("payment/openfeign/timeout")
String openFeignTimeout();
}
4: 消费的的OrderControlle
@RestController
@RequestMapping("order")
@CrossOrigin
@Slf4j
public class OrderController {
@Autowired
private FeignPaymentService feignPaymentService;
//http://localhost:8083/order/consumer/payment/get/1
@GetMapping("consumer/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
System.out.println("发起请求:");
return feignPaymentService.getPaymentById(id);
}
//http://localhost/order/consumer/payment/openfeign/timeout
@GetMapping("consumer/payment/openfeign/timeout")
public String openFeignTimeout(){
System.out.println("发起请求:");
return feignPaymentService.openFeignTimeout();
}
}