SpringCloud-Feign 远程调用

什么是Feign: Feign是NetFlix公司开源的Rest远程调用的客户端,可以实现http远程调用,像调用本地方法一样来调用远程的方法
SpringCloud引入了Feign并且集成了Ribbon实现了负载均衡
Feign的简单使用:
请首先参考之前的博客,关于微服务调用,Ribbon的负载均衡

  1. 引入Feign和Eureka-Client的jar包
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>

  1. 定义feign的接口,注意接口的url以及入参
package com.example.demo.feign.feign.service;

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

/**
 * @Auther: 星仔
 * @Date: 2019/3/17 09:35
 * @Description:
 */
 //value即在Eureka注册的微服务名称
@FeignClient(value = "hello-demo")
public interface GetHello {

    @GetMapping("/getHello/{name}")
    String getHello(@PathVariable("name") String name);
}

3.编写启动类

package com.example.demo.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients //Feign的声明注解
@EnableEurekaClient //EureKa的客户端注解
public class DemoFeignApplication {

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

}

4.测试类

package com.example.demo.feign.feign.client;

import com.example.demo.feign.feign.service.GetHello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: 星仔
 * @Date: 2019/3/17 09:43
 * @Description:
 */
@RestController
public class FeignTest {

    @Autowired
    private GetHello getHello;

    @RequestMapping("/feign")
    public String feignTest(){
        String xiaoming = getHello.getHello("xiaoming");
        return xiaoming;
    }
}

注意:

1、 启动类添加@EnableFeignClients注解,Spring会扫描标记了@FeignClient注解的接口,并生成此接口的代理
对象
2、 @FeignClient(value = XcServiceList.XC_SERVICE_MANAGE_CMS)即指定了cms的服务名称,Feign会从注册中
心获取cms服务列表,并通过负载均衡算法进行服务调用。
3、在接口方法 中使用注解@GetMapping("/cms/page/get/{id}"),指定调用的url,Feign将根据url进行远程调
用。

猜你喜欢

转载自blog.csdn.net/weixin_43794897/article/details/88614567