springcloud系列 (四)微服务之间的调用 Feign(声明式调用)

2 篇文章 0 订阅
2 篇文章 0 订阅

1.为了克服使用RestTemplate进行微服务负载均衡调用的复杂性,springcloud提供了声明式组件-----Feign;Feign是一个基于接口的编程方式,开发者只需要声明接口和配置注解,在调度接口方法时,springCloud就根据配置来调度对应的REST风格的请求,从其他微服务系统中获取数据,使用Feign首先需要在产品微服务中使用Maven引入依赖包:

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency> 
  1. 然后在springboot的启动文件中添加注解@EnableFeignClients,这个注解代表该项目会启动Feign客户端:
@SpringBootApplication
//@EnableDiscoveryClient
**@EnableFeignClients**
public class LearnProductApplication {

    public static void main(String[] args) {
        SpringApplication.run(LearnProductApplication.class, args);
    }

    // 初始化RestTemplate
    @LoadBalanced  //多节点负载均衡
    @Bean(name="restTemplate")
    public RestTemplate initRestTemplate(){
        return new RestTemplate();
    }

}
  1. 然后定义Feign接口:
@FeignClient("user")
public interface UserService {

    @GetMapping("/user/getUserPo/{id}")
    public UserPo getUser(@PathVariable("id") Long id);

    // POST方法请求用户微服务,并使用请求体参数
    @PostMapping("/user/insert")
    public Map<String,Object> addUser(@RequestBody UserPo user);

    // POST方法请求用户微服务,并使用URL参数和请求头参数
    @PostMapping("/user/update/{userName}")
    public Map<String,Object> updateName(@PathVariable("userName") String userName, @RequestHeader("id") Long id);
}
  1. 之后在ProductController中加入UserService接口对象的注入:
    @Autowired
    private UserService userService;
  1. 使用Feign调度用户微服务的REST端点:
@GetMapping("/feign")
    public List<UserPo> testFeign(){
        logger.info("testFeign");
        List<UserPo> list=new ArrayList<>();
        UserPo user=null;
        for (int i=0;i<10;i++){
            Long id=(long)(i+1);
            user=userService.getUser(id);
            list.add(user);
        }
        return list;
    } 
  1. 参考项目示例:https://gitee.com/manongfaner/cloud-maven-learn
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值