Spring Cloud 学习笔记08----服务消费者(Feign)(Finchley版本)

本文介绍了如何在SpringCloud中使用Feign作为服务消费者,实现基于接口的声明式HTTP客户端,集成Ribbon实现负载均衡,并结合Eureka进行服务注册。通过实例演示了Feign的简单入门和配置要点。
摘要由CSDN通过智能技术生成

概要

接上一篇《Spring Cloud 学习笔记06----断路器(Hystrix)(Finchley版本)》,今天我们来学习另外一种服务调用方式(Feign),之前我们介绍了 RestTemplate+Ribbon 消费服务的方式。

Feign简介

Feign 是一个声明式的伪Http客户端,它使得写Http 客户端变得更简单,使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign注解和JAX-RS注解,Feign 也支持可插拔的编码器和解码器,Spring Cloud 扩展了对Spring MVC的注解支持,在Spring Web 中同样使用HttpMessageConverters 。Feign 默认集成了Ribbon, 并和Eureka 结合,默认实现了负载均衡的效果。
简单来说:

  • Feign 采用的是基于接口的注解
  • Feign 整合了Ribbon, 具有负载均衡的能力
  • 整合了Hystrix,具有熔断能力。

快速入门

首先,沿用前面的服务注册中心(eureka-server)以及服务提供者(order-provider)。然后新建一个SpringBoot 项目,命名为service-feign。添加依赖

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--必须添加spring-boot-starter-web,否则注册失败-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

然后,在application.yml 加上如下配置,指定端口为8765,服务名为service-feign:

spring:
  application:
    name: service-feign
eureka:
  client:
    service-url:
#    用于指定注册中心的地址
      defaultZone: http://localhost:1111/eureka/
server:
  port: 8765

接着,我们在ServiceFeignApplication 中添加@EnableFeignClients以激活Feign。添加@EnableEurekaClient 以开启负载均衡,使其可以注册到Eureka 中。

。。。。。。。。。。。。。。。。。

版权原因,完整文章,请参考如下:Spring Cloud 学习笔记08----服务消费者(Feign)(Finchley版本)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值