• 谷粒商城学习——P90 调用远程服务


    谷粒商城学习——P20-27springcloud alibaba课程中已经学过openfeign调用远程服务的基本示例,重复的不在赘述

    被调用的远程controller接口指定了@PostMapping和@RequestBody,则调用的时候也需要指定这两个注解以保证签名一致

    关键代码:

    SpuBoundsController:接口提供方
    @RestController
    @RequestMapping("coupon/spubounds")
    public class SpuBoundsController {
        @Resource
        private SpuBoundsService spuBoundsService;
        @PostMapping("/save")
        public R save(@RequestBody SpuBoundsEntity spuBounds){
            spuBoundsService.save(spuBounds);
            return R.ok();
        }
    }
    View Code

    CouponFeignService:调用方的接口,指定远程调用信息
    @FeignClient("gulimall-coupon")
    public interface CouponFeignService {
    
        /**
         * 1、CouponFeignService.saveSpuBounds(spuBoundTo);
         *      1)、@RequestBody将这个对象转为json。
         *      2)、找到gulimall-coupon服务,给/coupon/spubounds/save发送请求。
         *          将上一步转的json放在请求体位置,发送请求;
         *      3)、对方服务收到请求。请求体里有json数据。
         *          (@RequestBody SpuBoundsEntity spuBounds);将请求体的json转为SpuBoundsEntity;
         * 只要json数据模型是兼容的。双方服务无需使用同一个to
         */
        @PostMapping("/coupon/spubounds/save")
        R saveSpuBounds(@RequestBody SpuBoundTo spuBoundTo);
    }
    View Code
    
    
    SpuInfoServiceImpl:调用具体实现
        @Resource
        private CouponFeignService couponFeignService;
    
        @Override
        public void savesupInfo(SpuSaveVo vo) {
            SpuBoundTo spuBoundTo = new SpuBoundTo();
            R r = couponFeignService.saveSpuBounds(spuBoundTo);
        }
    View Code

    PS课外补充:

    课堂上我没听到?自己测试得出一条经验:

    接口提供方为get请求时(参数可加RequestParam也可不加),接口调用方fenservice必须要对参数进行@RequestParam注解修饰,否则会调用接口失败,在接口提供方报:Request method 'POST' not supported,在接口调用方直接出一堆错405,

    关键代码:

    接口提供方CouponController

    @RefreshScope
    @RestController
    @RequestMapping("coupon/coupon")
    public class CouponController {
        @Autowired
        private CouponService couponService;
        @GetMapping("/test2")
        public R test2( @RequestParam("msg")String msg){
            return R.ok().put("coupon", "hello"+msg);
        }
    }

    接口调用方openfeignservice:

    @FeignClient("gulimall-coupon")
    public interface CouponFeignService {
        @RequestMapping("/coupon/coupon/test2")
        public R test2(@RequestParam("msg") String msg);
    }
  • 相关阅读:
    Java学习之路-Hessian学习
    Hessian知识学习总结(二)——Hessian的helloworld
    如何封装RESTful Web Service
    c#string为传值模式
    Acrobat 无法在本页面上执行OCR识别
    redis error It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING
    关于bootstrap的modal弹出层嵌套子Modal所引发的血案(转)
    项目学习——后台事件监听并触发相应操作
    Redis学习笔记
    正则表达式
  • 原文地址:https://www.cnblogs.com/yanan7890/p/14983182.html
Copyright © 2020-2023  润新知