Redis(案例四:购物车实现案例-Hash数据)
生活随笔
收集整理的這篇文章主要介紹了
Redis(案例四:购物车实现案例-Hash数据)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 購物車常見實現方式
- 購物?數據結構介紹
- 相關VO類和數據準備
- 數據源層
- json?具類
- 添加購物車接口、查看我的購物車、清空購物車
購物車常見實現方式
1、實現方式?:存儲到數據庫性能存在瓶頸
2、實現方式?:前端本地存儲-localstoragesessionstoragelocalstorage在瀏覽器中存儲key/value 對,沒有過期時間。sessionstorage在瀏覽器中存儲 key/value 對,在關閉會話窗?后將會刪除這些數據。
3、實現方式三:后端存儲到緩存如redis可以開啟AOF持久化防?重啟丟失(推薦)
購物?數據結構介紹
?個購物車里面,存在多個購物項,所以購物車結構是?個雙層Map:
Map<String,Map<String,String>>
第?層Map,Key是?戶id
第?層Map,Key是購物?中商品id,值是購物?數據
相關VO類和數據準備
VideoDO
@Data @NoArgsConstructor @AllArgsConstructor public class VideoDO {private int id;private String title;private String img;private int price;CartItemVO
public class CartItemVO {/*** 商品id*/private Integer productId;/*** 購買數量*/private Integer buyNum;/*** 商品標題*/private String productTitle;/*** 圖片*/private String productImg;/*** 商品單價*/private int price;/*** 總價格,單價+數量*/private int totalPrice;public int getProductId() {return productId;}public void setProductId(int productId) {this.productId = productId;}public Integer getBuyNum() {return buyNum;}public void setBuyNum(Integer buyNum) {this.buyNum = buyNum;}public String getProductTitle() {return productTitle;}public void setProductTitle(String productTitle) {this.productTitle = productTitle;}public String getProductImg() {return productImg;}public void setProductImg(String productImg) {this.productImg = productImg;}/*** 商品單價 * 購買數量** @return*/public int getTotalPrice() {return this.price * this.buyNum;}public int getPrice() {return price;}public void setPrice(int price) {this.price = price;}public void setTotalPrice(int totalPrice) {this.totalPrice = totalPrice;} }CartVO
import java.util.List;public class CartVO {/*** 購物項*/private List<CartItemVO> cartItems;/*** 購物車總價格*/private Integer totalAmount;/*** 總價格* @return*/public int getTotalAmount() {return cartItems.stream().mapToInt(CartItemVO::getTotalPrice).sum();}public List<CartItemVO> getCartItems() {return cartItems;}public void setCartItems(List<CartItemVO> cartItems) {this.cartItems = cartItems;} }數據源層
import net.xdclass.xdclassredis.model.VideoDO; import org.springframework.stereotype.Repository;import java.util.HashMap; import java.util.Map;@Repository public class VideoDao {private static Map<Integer,VideoDO> map = new HashMap<>();static {map.put(1, new VideoDO(1,"工業級PaaS云平臺+SpringCloudAlibaba 綜合項目實戰(完結)","https://xdclass.net",1099));map.put(2,new VideoDO(2,"玩轉新版高性能RabbitMQ容器化分布式集群實戰","https://xdclass.net",79));map.put(3,new VideoDO(3,"新版后端提效神器MybatisPlus+SwaggerUI3.X+Lombok","https://xdclass.net",49));map.put(4,new VideoDO(4,"玩轉Nginx分布式架構實戰教程 零基礎到高級","https://xdclass.net",49));map.put(5,new VideoDO(5,"ssm新版SpringBoot2.3/spring5/mybatis3","https://xdclass.net",49));map.put(6,new VideoDO(6,"新一代微服務全家桶AlibabaCloud+SpringCloud實戰","https://xdclass.net",59));}/*** 模擬從數據庫找* @param videoId* @return*/public VideoDO findDetailById(int videoId) {return map.get(videoId);} }json?具類
import com.fasterxml.jackson.databind.ObjectMapper;public class JsonUtil {private static final ObjectMapper MAPPER = new ObjectMapper();/*** 把對象轉字符串* @param data* @return*/public static String objectToJson(Object data){try {return MAPPER.writeValueAsString(data);}catch (Exception e){e.printStackTrace();}return null;}/*** json字符串轉對象* @param jsonData* @param beanType* @param <T>* @return*/public static <T> T jsonToPojo(String jsonData, Class<T> beanType){try {T t = MAPPER.readValue(jsonData,beanType);return t;}catch (Exception e){e.printStackTrace();}return null;}}添加購物車接口、查看我的購物車、清空購物車
import net.xdclass.xdclassredis.dao.VideoDao; import net.xdclass.xdclassredis.model.VideoDO; import net.xdclass.xdclassredis.util.JsonData; import net.xdclass.xdclassredis.util.JsonUtil; import net.xdclass.xdclassredis.vo.CartItemVO; import net.xdclass.xdclassredis.vo.CartVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList; import java.util.List;@RestController @RequestMapping("api/v1/cart") public class CartController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate VideoDao videoDao;@RequestMapping("add")public JsonData addCart(int videoId,int buyNum){//獲取購物車BoundHashOperations<String,Object,Object> myCart = getMyCartOps();Object cacheObj = myCart.get(videoId+"");String result = "";if(cacheObj!=null){result = (String)cacheObj;}//購物車沒這個商品if(cacheObj == null){CartItemVO cartItem = new CartItemVO();VideoDO videoDO = videoDao.findDetailById(videoId);cartItem.setBuyNum(buyNum);cartItem.setPrice(videoDO.getPrice());cartItem.setProductId(videoDO.getId());cartItem.setProductImg(videoDO.getImg());cartItem.setProductTitle(videoDO.getTitle());myCart.put(videoId+"",JsonUtil.objectToJson(cartItem));}else {//增加商品購買數量CartItemVO cartItemVO = JsonUtil.jsonToPojo(result,CartItemVO.class);cartItemVO.setBuyNum(cartItemVO.getBuyNum()+buyNum);myCart.put(videoId+"",JsonUtil.objectToJson(cartItemVO));}return JsonData.buildSuccess();}/*** 查看我的購物車*/@RequestMapping("mycart")public JsonData getMycart(){//獲取購物車BoundHashOperations<String,Object,Object> myCart = getMyCartOps();List<Object> itemList = myCart.values();List<CartItemVO> cartItemVOList = new ArrayList<>();for(Object item : itemList){CartItemVO cartItemVO = JsonUtil.jsonToPojo((String)item,CartItemVO.class);cartItemVOList.add(cartItemVO);}CartVO cartVO = new CartVO();cartVO.setCartItems(cartItemVOList);return JsonData.buildSuccess(cartVO);}/*** 清空我的購物車* @return*/@RequestMapping("clear")public JsonData clear(){String key = getCartKey();redisTemplate.delete(key);return JsonData.buildSuccess();}/*** 抽取我的購物車通用方法* @return*/private BoundHashOperations<String,Object,Object> getMyCartOps(){String key = getCartKey();return redisTemplate.boundHashOps(key);}private String getCartKey(){//用戶的id,從攔截器獲取int userId = 88;String cartKey = String.format("video:cart:%s",userId);return cartKey;}}總結
以上是生活随笔為你收集整理的Redis(案例四:购物车实现案例-Hash数据)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022年5家最佳(价格合理)网络喜剧网
- 下一篇: Redis(案例五:Set数据)