在微服务架构下,服务之间的调用必不可少,SpringCloud框架作为一个微服务解决方案,为我们提供了一个简单易用的组件,这个组件就是OpenFegin,OpenFegin是一个声明式的客户端,支持我们像调用本地方法一样去调用远程服务。
服务提供者
服务提供者端的代码正常书写即可,无需引入openfegin的相关东西。原因是这样:大家在Java代码中发起http请求都应该写过,我们可以使用OkHttp、HttpClient等,这些类只需要在消费者侧引入使用即可,并不需要在服务端去引入和使用。因此,OpenFegin大家就可以想象成一个发起Http请求的工具类,自然就可以理解为什么只需要在消费者端引入了。
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency></dependencies>
spring:application:name: provider-nacoscloud:nacos:server-addr: localhost:8848
server:port: 10001
@RestControllerpublic class ProviderController {@RequestMapping("test")public String test(){return "provider";}}
消费者端
消费者侧就需要引入openfegin,具体代码如下
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
server:port: 10002
spring:application:name: consumer-nacos-democloud:nacos:server-addr: localhost:8848
@EnableFeignClients@SpringBootApplicationpublic class ConsumerNacosDemoApplication {public static void main(String[] args) {SpringApplication.run(ConsumerNacosDemoApplication.class, args);}}
@FeignClient(name = "provider-nacos")public interface ProviderClient {@RequestMapping("test")String test();}
@RestControllerpublic class ConsumerNacosDemoController {@Autowiredprivate ProviderClient providerClient;@RequestMapping("testFegin")public String testFegin() {return providerClient.test();}}

