在Spring Cloud中,使用Eureka作为服务注册中心和发现机制的时候,可以通过以下步骤结合使用Feign Client:
1、在 pom.xml
中引入以下依赖:
<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>
2、配置Eureka客户端
在 application.yml
或 application.properties
中配置Eureka Client,将其注册到Eureka
spring:
application:
name: feign-client-demo
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
3、配置Feign Client
在 @SpringBootApplication
类型的主类上添加 @EnableFeignClients
注解开启Feign功能,并在定义Feign Client接口的类上使用 @FeignClient
注解声明要调用的服务,如下所示:
@SpringBootApplication
@EnableFeignClients
public class FeignClientApplication {
public static void main(String[] args) {
SpringApplication.run(FeignClientApplication.class, args);
}
@FeignClient(name = "eureka-client-demo")
public interface DemoClient {
@RequestMapping(value = "/", method = RequestMethod.GET)
String home();
}
}
4、调用Feign Client
在需要调用服务的地方,注入声明的Feign Client接口,然后调用其中的方法即可,如下所示:
@RestController
public class HomeController {
@Autowired
private DemoClient demoClient;
@GetMapping("/")
public String home() {
return demoClient.home();
}
}
以上为结合Eureka使用Feign Client的基本步骤,实际使用过程中还需要结合自己的业务进行具体的配置和调用。