打赏

谷粒商城学习——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);
}

 

posted @ 2021-07-07 19:22  每天都要学一点  阅读(177)  评论(0编辑  收藏  举报