栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud之Feign

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud之Feign

Feign主要是在消费者项目中进行伪装

1、导入依赖

    org.springframework.cloud
    spring-cloud-starter-openfeign
2、开启Feign
@EnableFeignClients//开启feign
@SpringCloudApplication
public class ConsumerApp {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args){
        SpringApplication.run(ConsumerApp.class,args);
    }
}
3、配置Feign客户端接口 Feign的实现需要配置伪装对应的请求类型、路径、参数、返回值,所以我们需要在消费者项目中单独创建一个客户端接口。 我们只需要提供接口,底层默认采用了jdk动态代理帮助我们自动实现了对应的功能。
@FeignClient("user-service/userController") //前缀
public interface ConsumerFeignClient {
    
    //这里和user-serivce项目中方法调用一致
    @GetMapping("/findUserById/{aa}")
    User findUserById(@PathVariable("aa") int aa);
    
}
4、Feign使用 在消费者项目Controller中注入刚才编写的接口
 @Autowired
 private ConsumerFeignClient consumerFeignClient;
编写feign类型代码
@GetMapping("/findUserByIds/{ids}")
public List findUserByIds(@PathVariable("ids") List ids){
    List list = new ArrayList<>();
    ids.forEach(id->{
        User user = consumerFeignClient.findUserById(id);
        list.add(user);
    });
    return list;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/301370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号