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

springCloud ribbon -10 ribbon 服务调用

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

springCloud ribbon -10 ribbon 服务调用

思路:可以将服务消费者调用服务提供者的地址改成服务名称,不必硬编码成ip 地址了,也不用使用DiscoveryClient 类

一, 将RestTemplate类引入注解@LoadBalanced
@SpringBootApplication
@EntityScan("com.zjk.order.entity")
@EnableEurekaClient
public class OrderApplication {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }
}
    @LoadBalanced
二,服务消费者使用服务提供者的服务名称请求
    
    @GetMapping(value = "/findByIdByRibbon/{Id}")
    public TbProduct findByIdByRibbon(@PathVariable Long Id){
        try {
            List instances = discoveryClient.getInstances("service-product");
            ServiceInstance serviceInstance = instances.get(0);
            TbProduct tbProduct = restTemplate.getForEntity("http://service-product/product/{Id}", TbProduct.class,Id).getBody();
            return tbProduct;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
            TbProduct tbProduct = restTemplate.getForEntity("http://service-product/product/{Id}", TbProduct.class,Id).getBody();

大家可以看出来,我们可以直接使用服务提供者的服务名称请求

 其实,ribbon 最重要的作用是负载均衡

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

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

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