spring-cloud-alibaba 集成Feign


前言

private final RestTemplate restTemplate;

UserDTO userDTO = restTemplate.getForObject(“http://user-center/users/{userId}”,UserDTO.class,userId);
通过这种RestTemplate 方式调用微服务,存在几个问题:
1.可读性差
2.复杂的url难以维护
3.被调微服务接口一旦有变化,修改复杂。

一、Feign是什么?

是Netflix的开源的声明式HTTP客户端

二、使用步骤

1.加依赖

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

2.加注解

代码如下(示例):

@MapperScan("com.itmuch")
@SpringBootApplication
@EnableFeignClients//加注解
public class ContentCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(ContentCenterApplication.class, args);
    }  
}

3.加yml配置

不用加

4.新建 要请求的微服务 的接口

import com.itmuch.contentcenter.domain.dto.user.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "user-center")//要请求的微服务的名称
public interface UserCenterFeignClient {

    /**
     * FeignClient最终拼成的url:
     * http://user-center/users/{id}
     * @param id
     * @return
     */
    @GetMapping("/users/{id}")
    UserDTO findById(@PathVariable Integer id);
}

5. 调用微服务

private final UserCenterFeignClient userCenterFeignClient;

UserDTO userDTO = userCenterFeignClient.findById(userId);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值