javascript
feign调用多个服务_Spring Cloud 快速入门系列之feign–微服务之间的调用
我們將一個(gè)大的應(yīng)用拆成多個(gè)小的服務(wù)之后,緊接著的一個(gè)問題就是,原本都在一個(gè)項(xiàng)目里,方法我可以隨便調(diào)用,但是拆開后,原來的方法就沒法直接調(diào)用了,這時(shí)候要怎么辦?
Spring Cloud提供了feign,能夠輕松解決這個(gè)問題,feign能讓我們調(diào)用遠(yuǎn)程服務(wù)方法就像調(diào)用本地方法一樣,調(diào)用者完全感覺不到實(shí)在調(diào)用遠(yuǎn)程服務(wù)。
其底層其實(shí)就是使用了RPC,對網(wǎng)絡(luò)的請求和響應(yīng)做了解析,在這里對RPC先不做講解,我們重點(diǎn)來了解如何使用feign來調(diào)用其他微服務(wù)。
feign這個(gè)功能是不是聽起來很神奇,但是用起來確實(shí)很簡單,我們一起來看看。
實(shí)操O(∩_∩)O
1、首先復(fù)制一個(gè)service-a的項(xiàng)目,我們起名叫service-b
2、在service-b的pom.xml文件中,添加feign的依賴
org.springframework.cloud
spring-cloud-starter-openfeign
3、在應(yīng)用主類添加@EnableFeignClients,開啟feign支持
package com.itzhimei.serviceb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceBApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceBApplication.class, args);
}
}
4、在service-b中添加一個(gè)抽象接口ServiceA
package com.itzhimei.serviceb.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("service-a")
public interface ServiceA {
@GetMapping(value = "/getInfo")
public String getInfo();
}
這個(gè)接口的作用就是,讓serviceb調(diào)用servicea的方法就像調(diào)用本地方法一樣。class上的注解@FeignClient(“service-a”),就表示通過serviceA的serviceId,找到serviceA服務(wù),通過@GetMapping(value = “/getInfo”)來對應(yīng)到serviceA中的方法。
5、最后就是調(diào)用ServiceA了,寫一個(gè)調(diào)用的Controller
package com.itzhimei.serviceb.controller;
import com.itzhimei.serviceb.feign.ServiceA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceBController {
@Autowired
ServiceA serviceA;
@RequestMapping(value="helloFeign", method = RequestMethod.GET)
public String helloFeign() {
return serviceA.getInfo();
}
}
輸出結(jié)果:名字是:張三,年齡是:20
到這里,微服務(wù)的相互調(diào)用就成功了,是不是超級簡單,通過幾步配置,就完成了原來復(fù)雜的網(wǎng)絡(luò)之間的調(diào)用。
總結(jié)
以上是生活随笔為你收集整理的feign调用多个服务_Spring Cloud 快速入门系列之feign–微服务之间的调用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 实现虚拟打印机 HP Color
- 下一篇: 网络虚拟化有几种实现方式_停车场管理系统