SpringCloud几种消费方式

0. 消费者访问生产者的三种远程调用方式

   RestTemplate/WebClient/Feign(默认开启负载均衡)

1. 使用RestTemplate

   1.创建 RestTemplateConfig   

       @Configuration

       public class RestTemplateConfig {

           @Bean

           @LoadBalanced

           public RestTemplate restTemplate() {

               return new RestTemplate();

           }

       }

    2.在Controller看使用RestTemplateConfig访问生产者

       String result = restTemplate.getForObject("http://user-service/sys/user/load?username=xmm", String.class);

2. 使用WebClient(略)

3. 使用Feign(建议)

   1.导入依赖

       <!--feign远程调用-->

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-openfeign</artifactId>

        </dependency>

   2.编写Feign接口

@Service

@FeignClient("user-service")

public interface UserFeign {

    @RequestMapping(value = "/sys/user/load2", method = RequestMethod.POST)

    String load2(UserVo userVo);

}

   3.启动类添加@EnableFeignClients注解

   4.调用Feign接口进行远程访问(消费者-->生产者)

   5.几个注意事项

     1.FeignClient接口,不能使用@GettingMapping之类的组合注解

     2.FeignClient接口中,如果使用到@PathVariable必须指定其value

     3.只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求,同时生产者必须支持POST请求并给参数添加@RequestBody注解

        建议使用公共vo+@RequestBody方式

     4.springcloud中feign访问其他服务并传参数出现错误的问题:status 405 reading LogisticsOrderService#getLogistics(Integer,String,Integer,Integer)

        当使用feign传参数的时候,需要加上@RequestParam注解,否则对方服务无法识别参数;    

        @GetMapping("/order/getLogistics")

        public ResponseObj getLogistics(

           @RequestParam(value = "logisticsType") Integer logisticsType,

           @RequestParam(value="token") String token,

           @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,

           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize);

4. Feign综合示例

    1~N个参数

      @RequestParam Long bookId

    1个复杂对象DTO

      生产者接受参数时要添加@RequestBody

      将DTO对象定义到公共模块  

       

附录一:远程调用的相关注解

   @PathVariable

   @RequestParam

   @RequestBody

   @RequestMapping

   注解RequestMapping中produces属性可以设置返回数据的类型以及编码,可以是json或者xml:

   @RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})

   @RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})

附录二:深入理解DTO、PO的概念、区别和用处

DTO(Data Transfer Object):数据传输对象,可以多个

将UI数据-->后台

将后台数据-->前端

PO(Persistent Object):持久化对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值