7 服务调用 Feign入门

7.1 Feign的简介

7.2 Feign使用

7.2.1 导入依赖

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

7.2.2 配置调用接口

package xx.study.sc.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**声明需要调用的微服务名称
 * @FeignClient
 *    name:服务提供者的名称
 *
 */
@FeignClient(name="service-product")
public interface ProductFeignClient {
    /**
     * 配置需要调用的微服务接口
     * 访问路径要写全  类+方法
     */
    @RequestMapping(value = "/product/buy",method = RequestMethod.GET)
    public String buy(@RequestParam String name);

}

7.2.3 在启动类上激活Feign

package xx.study.sc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    /**
     * 使用spring 提供的RestTemplate发送http请求到商品服务
     *    1。创建RestTemplate对象交给容器管理
     *    2。在使用的时候,调用其方法完成操作
     *
     */
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return  new RestTemplate();
    }


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

7.2.4 通过自动的接口调用远程服务

package xx.study.sc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import xx.study.sc.feign.ProductFeignClient;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
   

    @Autowired
    private ProductFeignClient productFeignClient;



    @RequestMapping(value = "/buyBanana",method = RequestMethod.GET)
    public String  buyBanana(@RequestParam String name){
        name=productFeignClient.buy(name);
        String returnVal="从feign收到"+name+"!!!";
        return returnVal;
    }


   
}

7.3 支持负载均衡

 

7.4 Feign和Ribbon的联系

 

7.5 请求压缩

7.6 日志设置

 

7.7 源码

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章