RestTemplate+ribbon与feign的用法区别

简单记录一下,maven依赖略过,此处说的是消费者方面的相关内容

RestTemplate+ribbon
启动类中
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class CloudOrderApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public IRule ribbonRule() {
        return new NacosRule();
    }
    public static void main(String[] args) {
        SpringApplication.run(CloudOrderApplication.class, args);
    }


}

controller中(部分代码)

   @Autowired
    private RestTemplate template;

    @RequestMapping("/getOrderById")
    public String getOrderById(String id) {
        String ID = id;
        Object forObject = template.getForObject("http://cloud-product/product/getProductById/"+id, String.class);
        return "订单服务查询:"+forObject;
    }
feign
feignservice
package com.example.cluodorder.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(value = "cloud-product")
public interface FeignProductService {

    @RequestMapping("/product/getProductById/{id}")
    String getProductInfo(@PathVariable String id);
}

controller中
@Autowired
    private FeignProductService feignProductService;

    @RequestMapping("/getOrderFromProduct/{id}")
    public String toFindProductInfo(@PathVariable String id) {
        return feignProductService.getProductInfo(id);
    }

前者在 template.getForObjec中写要请求的路径,其中不用ip+端口,用服务名称。
后者在feignservice中@FeignClient(value = “cloud-product”)为请求的服务名称,方法的 @RequestMapping("/product/getProductById/{id}")为要请求的接口,发起请求时,feign会自动拼接。

注意

@RequestMapping("/product/getProductById/{id}")中的接口名称要和远程调用的服务中接口名称一致。

@FeignClient(value = “cloud-product”)中的服务名前边千万不要加"/",要用“-”,不要用“_",不然会报错:

Service id not legal hostname
feign超时配置:

feign:
  client:
    config:
      default:
        connectTimeout: 100000
        readTimeout: 6000000

注意在这个配置里,feign是根级,不在任何其他插件下级,如下图所示:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值