一.购物车环境搭建:
1.创建 cart 服务:
1)搭建 cart 服务 环境:
0:流程 图示:
a:引入 公共依赖,并排除 mybatiis :
b:注册到服务中心,开启 OpenFeign,
c:放(bootstrap css image img js)到 nginx,路径为 :(/usr/local/nginx/html/static/cart)
d:配置 nginx.conf:
server {
listen 80;
server_name gulimall.com *.gulimall.com cart.baidu.com;
location / {
# root html;
# index index.html index.htm;
proxy_set_header Host $host;
root http://192.168.43.190:88;
}
location /static/ {
root /usr/local/nginx/html;
}
...
e:配置 网关:
- id: product_cart_server
uri: lb://gilimail-cart
predicates:
- Host=cart.baidu.com
- id: admin_cart
uri: lb://gilimail-cart
predicates:
- Path=/api/cart/**
filters:
- RewritePath=/api/cart/(?<segment>/?.*), /$\{segment}
f:配置 Hosts:
114.215.173.88 cart.baidu.com
g:配置 yml :
spring:
spring:
thymeleaf:
cache: false
prefix: "classpath:/templates/"
suffix: .html
cloud:
nacos:
discovery:
server-addr: 114.215.173.88:8848
application:
name: gilimail-cart
redis:
host: 114.215.173.88
server:
port: 15000
2.cart 验证用户是否登录:
1)拦截器进行拦截验证:
a:编写拦截器:
public class CartInterceptor implements HandlerInterceptor {
public static final ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object attribute = session.getAttribute(AuthServerConstant.GULI_LOGIN_USER);
if (attribute == null) {
//未登录
} else {
//已经登录
}
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
if (AuthServerConstant.GULI_LOGIN_USER.equals(c.getName())) {
}
}
threadLocal.set(null);
return true;
}
}
b:配置 拦截器 到容器中:
/**
* @Author zhangsan
* @Date 2021/4/16 4:21 下午
* @Version 1.0
*/
@Configuration
public class GulimallWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CartInterceptor()).addPathPatterns("/**");
}
}
2)拦截器 和 controller 传递数据:(ThreadLocal)
public static final ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
threadLocal.set(null);
UserInfoTo userInfoTo = threadLocal.get();
3)如果没有用户信息,返回时增加 cookie:
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
UserInfoTo userInfoTo = threadLocal.get();
if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
String userKey = userInfoTo.getUserKey();
Cookie cookie = new Cookie("user-key", userKey);
cookie.setDomain("");
cookie.setMaxAge(20);
response.addCookie(cookie);
}
}
3.cart 商品管理:
1)将商品 存到 redis,用的时候取出来,转换为 对象。
不用的时候,转换为 JSON,存回去。
1)重定向 携带数据:
RedirectAttributes redirectAttributes
redirectAttributes.addAttribute("aa", "bb");