曹耘豪的博客

Spring Cloud之Eureka配合Feign

  1. 注册中心Eureka Server
    1. 依赖
  2. 服务提供方
    1. 依赖
  3. 服务消费方
  4. 常见问题
    1. 1. UnknownHostException: service-provider

注册中心Eureka Server

依赖

1
implementation "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:3.0.1"

增加Eureka注解

Application.java
1
2
3
4
5
6
7
@SpringBootApplication
@EnableEurekaServer // 重要
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.yml
1
2
3
4
5
server:
port: 2000 #自定义
eureke:
client:
register-with-eureka:false

服务提供方

依赖

1
implementation "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:3.0.1"
1
2
3
4
5
6
7
8
9
10
11
server:
port: 8080
spring:
application:
name: {service-provider}
eureka:
client:
service-url:
defaultZone: http://localhost:2000/eureka/
instance:
prefer-ip-address: true

服务消费方

FeignClient

Api.java
1
2
3
4
5
6
@FeignClient(
name = "{service-provider}"
)
public interface Api {

}
Application.java
1
2
3
4
5
6
7
@SpringBootApplication
@EnableFeignClients // 激活feign client
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.yml
1
2
3
4
5
6
7
8
9
10
11
server:
port: 8081
spring:
application:
name: {service-consumer}
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:2000/eureka/
instance:
prefer-ip-address: true

常见问题

1. UnknownHostException: service-provider

  1. @FeignClient里使用了url参数,比如如果写url=http://{service-provider}/,是解析不到的
  2. 可能存在自定义Feign.Client,Spring Cloud里使用FeignBlockingLoadBalancerClient作为feign client,如果自定义的Feign.Client没有和服务发现联动,则会报错
   / 
  ,