假如现在有三个服务,入库,库存,出库,这三个微服务是互相隔离的,那么微服务和微服务之间如何互相调用呢?显然三个微服务都可以采用http通信,也就是可以采用Ribbon+restTemplate进行互相访问(具体如何使用上篇文章讲Ribbon组件有案例),但是这种方式对参数传递和使用都不是很方便,所以弃用此方式,采用Feign进行服务之间的调用,大大简化调用过程。
当我们使用feign客户端时,一般要做以下三件事情 :
1:使用注解@EnableFeignClients启用feign客户端;
2:使用注解@FeignClient 定义feign客户端;
3:使用注解@Autowired使用上面所定义feign的客户端;
1: 当我们把服务都注册到注册中心,那么首先我们要在项目中引入Feign的依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2:需要在启动类添加@EnableFeignClients注解
@EnableFeignClients//启用feign客户端 @EnableDiscoveryClient @EnableEurekaClient @SpringBootApplication(scanBasePackages = {"com.wcf.client"}) public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
3:使用注解@FeignClient 定义feign客户端
在调用方编写接口类 //在调用方编写接口类 @FeignClient(name = "provider-client") //name="provider-client"就是服务提供方暴露的接口名称 public interface FeignTestInterface { @RequestMapping(value="/provider-feign/getInfo",method = RequestMethod.GET) //value="/provider-feign/getInfo"就是服务方暴露的接口地址 List<String> getNameInfo(@RequestParam("names") String[] names); }
4:在调用方的controller中调用接口:
使用注解@Autowired使用上面所定义feign的客户端
@RestController public class FeignTestController { @Autowired private FeignTestInterface testInterface; @RequestMapping("/getNameInfo") public String config() { String[] names = {"李","王"}; return testInterface.getNameInfo(names).toString(); } }
5:在服务提供方提供如下方法:
@RestController @RequestMapping("/provider-feign") public class FeignTestController { @GetMapping("/getInfo") public List<String> Test(String[] names) { List<String> name = new ArrayList<String>(Arrays.asList(names)); name.add("郭"); return name; } }
服务提供方的配置文件如下
#服务端口 server.port=8077 #服务名称,#即为上面@FeignClient注解的name值(name = "provider-client") spring.application.name=provider-client #服务地址 eureka.instance.hostname=localhost #取消检索服务 eureka.client.fetch-registry=true eureka.client.register-with-eureka=true ? #注册中心路径,表示向这个注册中心注册服务,如果向注册中心注册多个服务,用“,”进行分隔 eureka.client.serviceUrl.defaultZone=http://localhost:8011/eureka
6:启动并访问
1:启动注册中心
2:启动服务提供方
3:提供调用方服务
4:访问地址:http://localhost:8091/getNameInfo
Feign机制就是使用了动态代理。首先,如果你对某个接口定义了@FeignClient注解,Feign就会针对这个接口创建一个动态代理对象,
该对象生成动态代理时会根据代理类方法生成一个RequestTemplate,该对象封装了HTTP请求需要的全部信息,如请求参数名、
请求方法等信息都在这个过程中确定,当请求该对象时候,会根据该对象封装成Request去调用Http Client(默认JDK的URLConnection,可以替换成Okhttp等Http框架),
然后再委托Ribbon的LoadBalanceClient做负载均衡,完成服务之间的调用。
欢迎关注公众号!公众号回复:入群 ,扫码加入我们交流群!
原文:https://www.cnblogs.com/LemonTree-123/p/14600825.html