登陆状态下加入购物车
生活随笔
收集整理的這篇文章主要介紹了
登陆状态下加入购物车
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
添加商品到購物車
頁面發起請求
已登錄情況下,向后臺添加購物車:
ly.http.post("/cart", {skuId: this.sku.id, num: this.num}).then(res=>{window.location = "http://www.learn.com/cart.html"; })這里發起的是Json請求。那么我們后臺也要以json接收。
編寫controller
先分析一下:
-
請求方式:新增,肯定是Post
-
請求路徑:/cart ,這個其實是Zuul路由的路徑,我們可以不管
-
請求參數:Json對象,包含skuId和num屬性
-
返回結果:無
在learn-gateway中添加路由配置:
CartService
這里我們不訪問數據庫,而是直接操作Redis。基本思路:
-
先查詢之前的購物車數據
-
判斷要添加的商品是否存在
-
存在:則直接修改數量后寫回Redis
-
不存在:新建一條數據,然后寫入Redis
-
代碼:
@Service public class CartService {@Autowiredprivate StringRedisTemplate redisTemplate;@Autowiredprivate GoodsClient goodsClient;static final String KEY_PREFIX = "learn:cart:uid:";static final Logger logger = LoggerFactory.getLogger(CartService.class);public void addCart(Cart cart) {// 獲取登錄用戶UserInfo user = LoginInterceptor.getLoginUser();// Redis的keyString key = KEY_PREFIX + user.getId();// 獲取hash操作對象BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);// 查詢是否存在Long skuId = cart.getSkuId();Integer num = cart.getNum();Boolean boo = hashOps.hasKey(skuId.toString());if (boo) {// 存在,獲取購物車數據String json = hashOps.get(skuId.toString()).toString();cart = JsonUtils.parse(json, Cart.class);// 修改購物車數量cart.setNum(cart.getNum() + num);} else {// 不存在,新增購物車數據cart.setUserId(user.getId());// 其它商品信息,需要查詢商品服務Sku sku = this.goodsClient.querySkuById(skuId);cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);cart.setPrice(sku.getPrice());cart.setTitle(sku.getTitle());cart.setOwnSpec(sku.getOwnSpec());}// 將購物車數據寫入redishashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));} }需要引入learn-item-interface依賴:
<dependency><groupId>com.learn.item</groupId><artifactId>learn-item-interface</artifactId><version>1.0.0-SNAPSHOT</version> </dependency>GoodClient
參照搜索工程,添加GoodClient,提供根據id查詢sku的接口:
@FeignClient("item-service") public interface GoodsClient extends GoodsApi { }在learn-item-service中的GoodsController添加方法:
@GetMapping("sku/{id}") public ResponseEntity<Sku> querySkuById(@PathVariable("id")Long id){Sku sku = this.goodsService.querySkuById(id);if (sku == null){return new ResponseEntity<>(HttpStatus.NOT_FOUND);}return ResponseEntity.ok(sku); }在learn-item-service中的GoodsService添加方法:
public Sku querySkuById(Long id) {return this.skuMapper.selectByPrimaryKey(id); }?
總結
以上是生活随笔為你收集整理的登陆状态下加入购物车的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 登陆状态购物车数据结构
- 下一篇: 查询购物车