Spring Cloud Netflix Feign 声明式服务调用

Posted by 彭超 on 2019-10-29
Estimated Reading Time 2 Minutes
Words 483 In Total
Viewed Times

Feign 简介

Feign 是一个声明式的伪 Http 客户端,它使得写 Http 客户端变得更简单。使用 Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用 Feign 注解和 JAX-RS 注解。Feign 支持可插拔的编码器和解码器。

Feign 默认集成了 Ribbon,并和 Eureka 结合,默认实现了 负载均衡 的效果。

引入依赖

在统一依赖管理项目中继承 Spring Boot 2.0.2.RELEASE 父项目,并声明 Spring Cloud Finchley.RC1 依赖版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

在当前项目 pom.xml 中主要添加依赖 spring-cloud-starter-netflix-eureka-serverspring-cloud-starter-openfeign

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

相关配置

application.yml 中添加以下配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
spring:
application:
name: hello-spring-cloud-web-admin-feign
thymeleaf:
cache: false
mode: LEGACYHTML5
encoding: UTF-8
servlet:
content-type: text/html

server:
port: 8765

eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

在 Application 入口类中添加 @EnableDiscoveryClient 注解开启扫描 Eureka 客户端,添加 @EnableFeignClients 开启 Feign 功能

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class WebAdminFeignApplication {
public static void main(String[] args) {
SpringApplication.run(WebAdminFeignApplication.class, args);
}
}

Service

通过 @FeignClient 声明调用哪个服务

1
2
3
4
5
6
7
@FeignClient(value = "hello-spring-cloud-service-admin")
public interface AdminService {

@RequestMapping(value = "hi", method = RequestMethod.GET)
String sayHi(@RequestParam("message") String message);

}

Controller

创建 Controller 对外提供调用的服务

1
2
3
4
5
6
7
8
9
10
11
12
@RestController
public class AdminController {

@Autowired
private AdminService adminService;

@RequestMapping(value = "hi", method = RequestMethod.GET)
public String sayHi(@RequestParam String message) {
return adminService.sayHi(message);
}

}

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !