springcloud之feign的使用

feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。

1.新建springboot子工程作为服务消费者,老规矩先导入相关依赖(ps:springcloud依赖在其父工程已经导入)

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>

2.在springboot启动类上加上注解@EnableEurekaClient和@EnableFeignClients

3.配置application.yml参数,端口为9091

#端口
server:
  port: 9091
#服务名称
spring:
  application:
    name: feign-consumer
eureka:
  client:
    service-url:
      defaultZone: http://www.aaa.com:10000/eureka,http://www.bbb.com:10001/eureka,http://www.ccc.com:10002/eureka

4.使用feign进行服务调用,先定义一个接口

//应用名称
@FeignClient("provider")
public interface MyFeign {

    //RequestMapping和方法名都与提供者那边一致
    @RequestMapping("/helloProvider")
    String hello();
}

controller:

@RestController
public class FeignConsumerController {

    @Autowired
    MyFeign myFeign;

    @RequestMapping("/helloFeign")
    public String helloFeign() {
        String result = myFeign.hello();
        return result;

    }
}

5.分别启动注册中心10000,两个服务提供者8080和8081,以及消费者9091,重复访问http://localhost:9091/helloFeign,发现依然有轮询,这是因为feign的底层集成了ribbon.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值