SpringCloud笔记05 OpenFeign服务消费者
coconutnut

https://blog.csdn.net/ThinkWon/article/details/103735751

Spring Cloud OpenFeign 是声明式的服务调用工具,它整合了Ribbon和Hystrix,拥有负载均衡和服务容错功能

创建feign-service模块

依赖

教程给的依赖是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

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

换成consul注册中心,改成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

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

发现没有spring cloud版本和依赖管理,加上

1
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
1
2
3
4
5
6
7
8
9
10
11
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

查看右侧Maven栏中没有红线

下一步

配置

教程给的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
server:
port: 8701

spring:
application:
name: feign-service

eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8001/eureka/

换成consul

1
2
3
4
5
6
7
8
9
10
11
12
13
#eureka:
# client:
# register-with-eureka: true
# fetch-registry: true
# service-url:
# defaultZone: http://localhost:8001/eureka/

cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}

@EnableFeignClients启动功能

1
2
3
4
5
6
7
8
9
10
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {

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

}

接口和控制器

根据源码补齐其它代码

负载均衡

启动consul服务器,两个user-service,feign-service服务

调用http://localhost:8701/user/1四次

交替打印

服务降级

前面UserFallbackService也拷过来了

1
2
3
@FeignClient(value = "user-service", fallback = UserFallbackService.class)
public interface UserService {
}

注释也加了

修改application.yml,开启Hystrix功能

1
2
3
4
#在Feign中开启Hystrix
feign:
hystrix:
enabled: true

关闭两个user-service服务,重新启动feign-service

调用http://localhost:8701/user/1进行测试

发现被降级

日志打印功能

用FeignConfig配置类

在application.yml中配置需要开启日志的Feign客户端

可设置日志级别

总结