OpenFeign使用代替RestTemplate

由于RestTemplate来请求其他服务时仍然会带有http和//等符号,不符合java对象的操作

所以用OpenFeign来代替

第一步,导入OpenFeign的依赖

需要先在父工程添加SpringCloud的依赖进行版本管理

SpringCloud

    <dependencyManagement>
        <dependencies>
            <!--springCloud依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

OpenFeign:

<!--OpenFeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

第二步,根据服务创建client接口

哪个服务要请求其他服务,就在哪个服务里面创建client

例如有三个服务,服务名分别为user-service,book-service。borrow-service需要调用其他两个,就在borrow-service里创建两个client接口,如图

 Client接口内容如下,以UserClient为例

import com.test.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("user-service")   //服务名叫什么,这里就填什么
public interface UserClient {

    /**
     * 需要请求哪个方法就按照controller的写法,但是改为接口的类型
     * @param uid
     * @return
     */
    @GetMapping("/user/{uid}") //这里的路径要填对,有可能之前Controller是通过类上面的和这里的拼接的,这里要写全
    public User getByID(@PathVariable int uid);
}

第三步,在启动类上加上@EnableFeignClients

 第四步,使用

原先用法是注入RestTemplate,然后通过地址的方法来请求

现在注入Client接口,通过调用方法来请求

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值