SpringCloud之Feign远程接口映射的实现
一.简介
SpringCloud是基于Restful的远程调用框架,引入Ribbon负载均衡组件后还需要客户端使用RestTemplate调用远程接口,操作起来还显得繁琐。SpringCloud提供了远程接口映射,将远程Restful服务映射为远程接口,消费端注入远程接口即可实现方法调用。
二.流程
1.新建远程接口映射模块service-api,并引入Feign接口映射依赖
org.springframework.cloud spring-cloud-starter-feign
2.编写接口映射接口
packagecom.vincent.service;
importorg.springframework.cloud.netflix.feign.FeignClient;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
@FeignClient("SERVICE-USER")
@RequestMapping("/service-user")
publicinterfaceIUserService{
@GetMapping("/detail")
Objectdetail(@RequestParam("id")Integerid);
}
3.配置消费端application.yml
server: port:9001 eureka: client: service-url: defaultZone:http://localhost:7001/service-eureka/eureka register-with-eureka:false
4.消费端添加映射模块依赖
com.vincent service-api 1.0-SNAPSHOT
5.客户端注入需要使用的服务接口映射
packagecom.vincent.controller;
importcom.vincent.service.IUserService;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RestController;
@RestController
publicclassUserController{
@Autowired
privateIUserServiceuserService;
@GetMapping("/detail")
publicObjectdetail(Integerid){
returnthis.userService.detail(id);
}
}
5.编写消费端启动类
packagecom.vincent;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;
importorg.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients({"com.vincent.service"})
@EnableEurekaClient
publicclassConsumerApp{
publicstaticvoidmain(String[]args){
SpringApplication.run(ConsumerApp.class,args);
}
}
@EnableFeignClients定义Feign接口映射扫描包,IOC容器会自动创建接口实现类
6.访问http://localhost:9001/detail?id=1
三.总结
Feign接口映射服务端Restful接口会自动依赖Ribbon组件,实现客户端负载均衡。使用接口调用消费端远程接口就像调用本地方法一样。
到此这篇关于SpringCloud之Feign远程接口映射的实现的文章就介绍到这了,更多相关SpringCloudFeign远程接口映射内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。