openFeign 踩坑 服务调用实体类无法接收问题
本菜鸟在学习nacos和feign的整合的个人小项目中:想在消费端口80用feign调注册在nacos的服务提供者8081的数据写入方法,传入的是一个实体类。
运行结果为:
于是本菜鸟便在调用侧的controller层和被调用侧 controller层写了 log.info(),看看到底是怎么回事:
调用的service层:
@FeignClient(name = “commodity-provider”)
public interface CommodityService {
@RequestMapping(value = "/commodity/addCommodity",method = RequestMethod.POST)
CommonResult addCommodity(@RequestBody Commodity commodity);
}
调用的controller层:
@RestController
@Slf4j
@Api
public class CommodityController {
@Autowired
MallService mallService;
@GetMapping("/client/Commodity/addCommodity")
@ApiOperation("Feign测试")
public CommonResult addCommodity1(Commodity commodity){
log.info("参数={}",commodity);
mallService.addCommodity(commodity);
return new CommonResult(200, "客户端调新增商品服务成功!");
}
}
结果:
被调用的controller层:
@RestController
@Api
@Slf4j
public class CommodityController {
@Autowired
CommodityService commodityService;
@PostMapping("/commodity/addCommodity")
@ApiOperation("新增商品")
public CommonResult addCommodity(Commodity commodity){
commodityService.addCommodity(commodity);
log.info("openfeign:{} ",commodity);
log.info("***新增商品成功");
return new CommonResult(200,"新增商品成功");
}
}
结果:
从这里看的话,是调用的服务无法接收到实体类的参数所导致的。
然后通过各种查资料 发现需要在被调用的controller层和调用的service层添加一个@RequestBody注解
@FeignClient(name = "commodity-provider")
public interface CommodityService {
@RequestMapping(value = "/commodity/addCommodity",method = RequestMethod.POST)
CommonResult addCommodity(@RequestBody Commodity commodity);
}
@RestController
@Api
@Slf4j
public class CommodityController {
@Autowired
CommodityService commodityService;
@PostMapping("/commodity/addCommodity")
@ApiOperation("新增商品")
public CommonResult addCommodity(@RequestBody Commodity commodity){
commodityService.addCommodity(commodity);
log.info("openfeign:{} ",commodity);
log.info("***新增商品成功");
return new CommonResult(200,"新增商品成功");
}
}
再运行发现成功了
原理本菜鸟不是很了解,用知道的朋友可以在评论告诉我!!!,谢谢!!