【springcloud】Feign的使用

什么是Feign

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

简而言之:

  • Feign 采用的是基于接口的注解
  • Feign 整合了ribbon

使用步骤

  1. 添加feign依赖
                <dependency>
    			<groupId>org.springframework.cloud</groupId>
    			<artifactId>spring-cloud-starter-openfeign</artifactId>
    		</dependency>
  2. 在启动类上添加注解:@EnableFeignClients

  3. 编写接口

    package cn.aaralyn.sellorder.client;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    
    /**
     * @Auther: aaralyn
     * @Date: 2018/7/27 13:42
     * @Description:
     */
    @FeignClient(name = "product")//name为eureka中注册的服务名称
    public interface ProductClient {
    
        @GetMapping("msg")
        String getProductMsg();
    }

在接口上添加@FeignClient注解,name为服务的名称,接口中的方法为服务中对应方法,方法名可以不一致,但是url映射与返回值类型需要一致

   4. 测试

package cn.aaralyn.sellorder.controller;

import cn.aaralyn.sellorder.client.ProductClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: aaralyn
 * @Date: 2018/7/27 10:03
 * @Description:
 */
@RestController
public class ClientController {
   
    @Autowired
    private ProductClient productClient;
    @GetMapping("getMsg")
    public String getMsg() {
    
        return productClient.getProductMsg();
    }

}

 

猜你喜欢

转载自blog.csdn.net/weixin_39860498/article/details/81236019