【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
**开源地址:https://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB **
skuId:2131241,
title:“小米6”,
image:“”,
price:190000,
num:1,
ownSpec:“{“机身颜色”:“陶瓷黑尊享版”,“内存”:“6GB”,“机身存储”:“128GB”}”
}
另外,购物车中不止一条数据,因此最终会是对象的数组。即:
[
{…},{…},{…}
]
3.1.2.web本地存储
知道了数据结构,下一个问题,就是如何保存购物车数据。前面我们分析过,可以使用Localstorage来实现。Localstorage是web本地存储的一种,那么,什么是web本地存储呢?
什么是web本地存储?
web本地存储主要有两种方式:
-
LocalStorage:localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。
-
SessionStorage:sessionStorage 方法针对一个 session 进行数据存储。当用户关闭浏览器窗口后,数据会被删除。
LocalStorage的用法
语法非常简单:
localStorage.setItem(“key”,“value”); // 存储数据
localStorage.getItem(“key”); // 获取数据
localStorage.removeItem(“key”); // 删除数据
ss = JSON.stringify({age:12,sex:“male”})
‘{“age”:12,“sex”:“male”}’
localStorage.setItem(“name”,ss)
undefined
localStorage.getItem(“name”)
‘{“age”:12,“sex”:“male”}’
注意:localStorage和SessionStorage都只能保存字符串。
不过,在我们的common.js中,已经对localStorage进行了简单的封装:
示例:
ly.store.set(“aa”,{age:14,sex:“male”})
undefined
ly.store.get(“aa”)
{age: 14, sex: ‘male’}
3.1.3.获取num
添加购物车需要知道购物的数量,所以我们需要获取数量大小。我们在Vue中定义num,保存数量:
然后将num与页面的input框绑定,同时给+
和-
的按钮绑定事件:
编写事件:
3.2.1.点击事件
我们看下商品详情页:
现在点击加入购物车会跳转到购物车成功页面。
不过我们不这么做,我们绑定点击事件,然后实现添加购物车功能。
addCart方法中判断用户的登录状态:
3.2.2.获取数量,添加购物车
addCart(){
// 判断登录状态
ly.http.get(“/auth/verify”)
.then(resp => {
})
.catch(() => {
// 未登录,添加到localstorage
// 1、查询本地购物车
const carts = ly.store.get(“carts”) || [];
let cart = carts.find(c => c.skuId === this.sku.id);
// 2、判断是否存在
if(cart){
// 3、存在,改数量
cart.num += this.num;
}else {
// 4、不存在,新增
cart = {
skuId: this.sku.id,
title: this.sku.title,
image: this.images[0],
price: this.sku.price,
num: this.num,
ownSpec: JSON.stringify(this.sku.ownSpec)
};
carts.push(cart);
}
// 把carts写回localstorage
ly.store.set(“carts”, carts);
// 跳转
window.location.href = “http://www.leyou.com/cart.html”;
});
}
结果:
添加完成后,页面会跳转到购物车结算页面:cart.html
3.3.1.校验用户登录
因为会多次校验用户登录状态,因此我们封装一个校验的方法:
在common.js中:
3.3.2.查询购物车
页面加载时,就应该去查询购物车。cart.html中
var cartVm = new Vue({
el: “#cartApp”,
data: {
ly,
carts: [],// 购物车数据
},
created() {
this.loadCarts();
},
methods: {
loadCarts() {
// 先判断登录状态
ly.verifyUser()
.then(() => {
// 已登录
})
.catch(() => {
// 未登录
this.carts = ly.store.get(“carts”) || [];
this.selected = this.carts;
})
}
}
components: {
shortcut: () => import(“/js/pages/shortcut.js”)
}
})
刷新页面,查看控制台Vue实例:
3.5.2.渲染到页面
接下来,我们在页面中展示carts的数据:
页面位置:
修改后:
要注意,价格的展示需要进行格式化,这里使用的是我们在common.js中定义的formatPrice方法:
效果:
我们给页面的 +
和 -
绑定点击事件,修改num 的值:
两个事件:
increment© {
c.num++;
ly.verifyUser()
.then(() => {
// TODO 已登录,向后台发起请求
})
.catch(() => {
// 未登录,直接操作本地数据
ly.store.set(“carts”, this.carts);
})
},
decrement© {
if (c.num <= 1) {
return;
}
c.num–;
this.verifyUser()
.then(() => {
// TODO 已登录,向后台发起请求
})
.catch(() => {
// 未登录,直接操作本地数据
ly.store.set(“carts”, this.carts);
})
},
给删除按钮绑定事件:
点击事件中删除商品:
deleteCart(i) {
ly.verifyUser()
.then(() => {
// 已登录
})
.catch(() => {
// 未登录
this.carts.splice(i, 1);
ly.store.set(“carts”, this.carts);
})
}
在页面中,每个购物车商品左侧,都有一个复选框,用户可以选择部分商品进行下单,而不一定是全部:
我们定义一个变量,记录所有被选中的商品:
3.8.1.选中一个
我们给商品前面的复选框与selected绑定,并且指定其值为当前购物车商品:
3.8.2.初始化全选
我们在加载完成购物车查询后,初始化全选:
3.8.4.总价格
然后编写一个计算属性,计算出选中商品总价格:
computed: {
totalPrice() {
return this.selected.map(c => c.num * c.price).reduce((p1, p2) => p1 + p2, 0);
}
}
在页面中展示总价格:
效果:
===================================================================
4.1.1.创建购物车的微服务
4.1.2.pom依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns=“http://maven.apache.org/POM/4.0.0”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
leyou
com.leyou.parent
1.0.0-SNAPSHOT
4.0.0
com.leyou.service
ly-cart
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.boot
spring-boot-starter-data-redis
4.1.3.配置文件
server:
port: 8088
spring:
application:
name: cart-service
redis:
host: 192.168.206.66
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
registry-fetch-interval-seconds: 5
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
instance-id: e u r e k a . i n s t a n c e . i p − a d d r e s s . {eureka.instance.ip-address}. eureka.instance.ip−address.{server.port}
lease-renewal-interval-in-seconds: 3
lease-expiration-duration-in-seconds: 10
4.1.4.启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class LyCartApplication {
public static void main(String[] args) {
SpringApplication.run(LyCartApplication.class, args);
}
}
4.1.5.添加到网关的路由当中
===================================================================
接下来,我们完成已登录购物车。
在刚才的未登录购物车编写时,我们已经预留好了编写代码的位置,逻辑也基本一致。
购物车系统只负责登录状态的购物车处理,因此需要添加登录校验,我们通过JWT鉴权即可实现。
5.1.1.引入JWT相关依赖
我们引入之前写的鉴权工具:ly-auth-common
com.leyou.auth
ly-auth-common
1.0.0-SNAPSHOT
5.1.2.配置公钥
ly:
jwt:
pubKeyPath: C:\Users\ZHENG\Desktop\leyou_msgrs\rsa\rsa.pub # 公钥地址
cookieName: LY_TOKEN # cookie的名称
5.1.3.加载公钥
package com.leyou.cart.config;
import com.leyou.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct;
import java.security.PublicKey;
@Data
@ConfigurationProperties(prefix = “ly.jwt”)
@Slf4j
public class JwtProperties {
private String pubKeyPath;// 公钥
private PublicKey publicKey; // 公钥
private String cookieName;
@PostConstruct
public void init(){
try {
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
} catch (Exception e) {
log.error(“初始化公钥失败!”, e);
throw new RuntimeException();
}
}
}
5.1.4.编写过滤器
引入依赖:
com.leyou.common
ly-common
1.0.0-SNAPSHOT
代码:
因为很多接口都需要进行登录,我们直接编写SpringMVC拦截器,进行统一登录校验。同时,我们还要把解析得到的用户信息保存起来,以便后续的接口可以使用。
package com.leyou.interceptor;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
private JwtProperties prop;
private static final ThreadLocal tl = new ThreadLocal<>();
public UserInterceptor(JwtProperties prop) {
this.prop = prop;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
//获取Cookie
String token = CookieUtils.getCookieValue(request, prop.getCookieName());
try {
//解析token
UserInfo user = JwtUtils.getUserInfo(prop.getPublicKey(), token);
//传递User
tl.set(user);
//放行
return true;
} catch (Exception e) {
log.error(“[购物车服务]解析用户身份失败”, e);
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex)
throws Exception {
tl.remove();
}
public static UserInfo getLoginUser() {
return tl.get();
}
}
注意:
-
这里我们使用了
ThreadLocal
来存储查询到的用户信息,线程内共享,因此请求到达Controller
后可以共享User -
并且对外提供了静态的方法:
getLoginUser()
来获取User信息
5.1.5.配置过滤器
配置SpringMVC,使过滤器生效:
package com.leyou.cart.config;
import com.leyou.interceptor.UserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private JwtProperties prop;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserInterceptor(prop)).addPathPatterns(“/**”);
}
}
数据结构设计
当用户登录时,我们需要把购物车数据保存到后台,可以选择保存在数据库。但是购物车是一个读写频率很高的数据。因此我们这里选择读写效率比较高的Redis作为购物车存储。
Redis有5种不同数据结构,这里选择哪一种比较合适呢?
-
首先不同用户应该有独立的购物车,因此购物车应该以用户的作为key来存储,Value是用户的所有购物车信息。这样看来基本的
k-v
结构就可以了。 -
但是,我们对购物车中的商品进行增、删、改操作,基本都需要根据商品id进行判断,为了方便后期处理,我们的购物车也应该是
k-v
结构,key是商品id,value才是这个商品的购物车信息。
综上所述,我们的购物车结构是一个双层Map:Map<String,Map<String,String>>
-
第一层Map,Key是用户id
-
第二层Map,Key是购物车中商品id,值是购物车数据
-
Map<string,Map<String,String>>