Feign Client without Eureka

2019-07-22 11:28:23 浏览数 (2)

Feign Client相比Rest Template可以自动实现负载均衡,而且接口使用也更加友好,但是一般情况下Feign Client都需要依赖eureka。其实我们也可以在没有eureka的环境下,直接使用Feign Client。既用到了Feign Client的好处,又为将来切换到Spring Cloud做好预备.

添加依赖

代码语言:javascript复制
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.netflix.archaius</groupId>
    <artifactId>archaius-core</artifactId>
    <version>0.7.6</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.1-jre</version>
</dependency>

定义Feign接口

  • HomeApi
代码语言:javascript复制
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(value = "home", path = "/home")
public interface HomeApi {
    @GetMapping("/ping")
    String ping();
}

注意:这里的value = "home"需要与后面配置文件中的home一致

配置文件

  • application.yml
代码语言:javascript复制
eureka:
  client:
    enabled: false

home:
  ribbon:
    listOfServers: http://localhost:8081

上面配置文件中home interface的目标地址是http://localhost:8081,如果有多个的话,可以使用逗号(,)隔开

接口调用

  • FeignWithoutEurekaApplication
代码语言:javascript复制
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

import javax.annotation.Resource;

@EnableFeignClients
@SpringBootApplication
public class FeignWithoutEurekaApplication implements ApplicationRunner {

    @Resource
    private HomeApi homeApi;

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

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(homeApi.ping());
    }
}

注意需要添加注解@EnableFeignClients

执行结果

标准输出中输出

代码语言:javascript复制
success

参考

  • 基于Eureka的远程调用 - Feign Client

0 人点赞