掘金日新计划 · 8 月更文挑战第22天--服务整合

71 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情

今天我们在good-price整合一下服务,在good-price调用good-list服务,进行接口数据数据的调用。来吧,各位老铁,跟着我上车。

1.在good-price的实体包entity创建GoodAndPrice实体类

image.png 实体类包括商品自增ID,商品ID,商品name和商品价格,这边创建实体,要记得 implements Serializable

package com.imooc.good.entity;

import java.io.Serializable;

public class GoodAndPrice implements Serializable {
    Integer id;
    Integer goodId;
    String name;
    Integer price;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getGoodId() {
        return goodId;
    }

    public void setGoodId(Integer goodId) {
        this.goodId = goodId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }
}

2.在service/impl的GoodPriceServiceImpl重写getGoodsAndPrice方法

image.png

@Override
public List<GoodAndPrice> getGoodsAndPrice() {
    List<GoodAndPrice> goodAndPricesList = new ArrayList<>();
    List<Good> goods = goodListClient.goodList();
    for (int i = 0; i < goods.size(); i++) {
        Good good = goods.get(i);
        if(good!=null){
           GoodPrice goodPrice =  getGoodPrice(good.getGoodId());
           GoodAndPrice goodAndPrice = new GoodAndPrice();
           goodAndPrice.setPrice(goodPrice.getPrice());
           goodAndPrice.setName(good.getGoodName());
           goodAndPrice.setId(good.getId());
           goodAndPrice.setGoodId(good.getGoodId());
            goodAndPricesList.add(goodAndPrice);
        }
    }
    return goodAndPricesList;
}

代码说明:
引用:GoodListClient goodListClient,用来获取商品列表
通过:GoodPrice goodPrice = getGoodPrice(good.getGoodId)来获取商品价格
定义GoodAndPrice对象,用来设置返回值 GoodAndPrice goodAndPrice = new GoodAndPrice();

3.在service定义getGoodsAndPrice方法

image.png

List<GoodAndPrice> getGoodsAndPrice();

4.在controller新增goodAndPrice方法,来获取接口数据

image.png

@GetMapping("goodsAndPrice")
public List<GoodAndPrice> getGoodAndPrice(){
       return goodPriceService.getGoodsAndPrice();
}

5.重启good-price

image.png

6.打开浏览器,测试api接口

http://localhost:8083/goodsAndPrice 这时候,我们发现商品价格price已经返回了,说明我们的服务之间的调用已经正常了 image.png