其他分享
首页 > 其他分享> > Spring cloud使用 - openfeign

Spring cloud使用 - openfeign

作者:互联网

openfeign

openfiegn是一个声明式的REST客户端,也就是它可以在微服务中替换 RestTemplate

引入

  1. pom.xml中新增依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. Application中,添加@EnableFeignClients注解
  2. 新建一个Java接口FeignConsumerService,内容如下:
@FeignClient("consumerservice")
public interface FeignConsumerService {
    @RequestMapping(method = RequestMethod.GET, value = "/consumer/{id}")
    TConsumer queryById(@PathVariable("id") Integer id);
}

在实现类中使用:
引入bean

@Resource
private FeignConsumerService feignConsumerService;

方法调用:

TConsumer tConsumer = feignConsumerService.queryById(consumerId);

这样我们就由之前调用微服务的方式由RestTemplate的方式改成了调用接口的方式。

// 使用restTemplate
String url = "http://consumerservice/consumer/" + consumerId;
TConsumer tConsumer = restTemplate.getForObject(url, TConsumer.class);

// 使用 openfeign
TConsumer tConsumer = feignConsumerService.queryById(consumerId);

从这两种方式可以比较出,使用openfeign我们可以像调用服务的方式一样,服务.方法去调用微服务,不会在业务代码中看到有url这样的标识。

标签:调用,openfeign,Spring,consumerId,TConsumer,id,cloud
来源: https://www.cnblogs.com/geoary/p/16216050.html