SpringCloud 实战三:服务消费者(Feign)

Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。比如:
首先微服务ProductApplication 中加入 @EnableFeignClients

 
package com.cloud.product;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;


@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ProductApplication {

    public static void main(String[] args){
        SpringApplication.run(ProductApplication.class,args);
    }

}

关于微服务Product 中Controller

package com.cloud.product.controller;

import com.cloud.product.feign.ApiGetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/index")
public class ProductController {


    @Autowired
    ApiGetService apiGetService;

    @GetMapping("/hello")
    public String hello() {
        return "product say hello";
    }

    @GetMapping("/testFeign")
    public String feignApiGeteWay() {
        return apiGetService.testApiHello();
    }

}

采用Feign  相关配置如下

package com.cloud.product.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(value = "API-GATEWAY")
public interface ApiGetService {

    @GetMapping("/api/hello")
    String testApiHello();
}

API-GATEWAY是注册在EUREKA中的服务,/api/hello 是该微服务下的接口 

请求微服务中PRODUCT  的 /testFeign接口即可调用  微服务API-GATEWAY 服务下 /api/hello

总结
通过Feign, 我们能把HTTP远程调用对开发者完全透明,得到与调用本地方法一致的编码体验。这一点与阿里Dubbo中暴露远程服务的方式类似,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。如果是在用Spring Cloud Netflix搭建微服务,那么Feign无疑是最佳选择。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值