From 329d74a21cea3caaa33acb987607034d406336d9 Mon Sep 17 00:00:00 2001 From: Bunny <1319900154@qq.com> Date: Thu, 28 Dec 2023 12:47:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B4=AD=E7=89=A9=E8=BD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/misc.xml | 1 - .idea/workspace.xml | 101 +++++++++++------- ...ava => EnableUserWebMvcConfiguration.java} | 4 +- .../interceptor/UserLoginAuthInterceptor.java | 7 +- .../cn/bunny/getway/config/RedisConfig.java | 32 ++++++ .../bunny/getway/filter/AuthGlobalFilter.java | 52 +++++---- .../src/main/resources/application-dev.yml | 4 +- spzx-service/service-cart/pom.xml | 6 +- .../bunny/web/controller/CartController.java | 27 +++++ .../cn/bunny/web/service/CartService.java | 6 ++ .../web/service/impl/CartServiceImpl.java | 63 +++++++++++ .../src/main/resources/application-dev.yml | 6 +- .../src/main/resources/application-dev.yml | 2 + .../src/main/java/cn/bunny/user/User.java | 4 +- .../user/controller/UserinfoController.java | 2 +- .../service/impl/UserinfoServiceImpl.java | 8 +- .../src/main/resources/application-dev.yml | 2 + 17 files changed, 248 insertions(+), 79 deletions(-) rename spzx-common/common-service/src/main/java/cn/bunny/anno/{EnableUserLoginAuthInterceptor.java => EnableUserWebMvcConfiguration.java} (90%) create mode 100644 spzx-server-gateway/src/main/java/cn/bunny/getway/config/RedisConfig.java create mode 100644 spzx-service/service-cart/src/main/java/cn/bunny/web/controller/CartController.java create mode 100644 spzx-service/service-cart/src/main/java/cn/bunny/web/service/CartService.java create mode 100644 spzx-service/service-cart/src/main/java/cn/bunny/web/service/impl/CartServiceImpl.java diff --git a/.idea/misc.xml b/.idea/misc.xml index 0abcc97..9c8dcca 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 9cad354..65dd89a 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,8 +4,24 @@ - + + + + + + + + + + + + + + + + + + - @@ -112,7 +128,7 @@ - + + - @@ -171,7 +187,9 @@ - + + + - @@ -323,7 +349,8 @@ - diff --git a/spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserLoginAuthInterceptor.java b/spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserWebMvcConfiguration.java similarity index 90% rename from spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserLoginAuthInterceptor.java rename to spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserWebMvcConfiguration.java index d01a28f..95b1dd9 100644 --- a/spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserLoginAuthInterceptor.java +++ b/spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserWebMvcConfiguration.java @@ -12,5 +12,5 @@ import java.lang.annotation.Target; @Retention(value = RetentionPolicy.RUNTIME) @Target(value = ElementType.TYPE) @Import(value = {UserLoginAuthInterceptor.class, UserWebMvcConfiguration.class}) -public @interface EnableUserLoginAuthInterceptor { -} +public @interface EnableUserWebMvcConfiguration { +} \ No newline at end of file diff --git a/spzx-common/common-service/src/main/java/cn/bunny/interceptor/UserLoginAuthInterceptor.java b/spzx-common/common-service/src/main/java/cn/bunny/interceptor/UserLoginAuthInterceptor.java index d814bc1..f74b446 100644 --- a/spzx-common/common-service/src/main/java/cn/bunny/interceptor/UserLoginAuthInterceptor.java +++ b/spzx-common/common-service/src/main/java/cn/bunny/interceptor/UserLoginAuthInterceptor.java @@ -11,14 +11,15 @@ import org.springframework.web.servlet.HandlerInterceptor; public class UserLoginAuthInterceptor implements HandlerInterceptor { + @Resource - private RedisTemplate redisTemplate; + private RedisTemplate redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 如果token不为空,那么此时验证token的合法性 - String userInfoJSON = (String) redisTemplate.opsForValue().get("user:spzx:" + request.getHeader("token")); + String userInfoJSON = redisTemplate.opsForValue().get("user:spzx:" + request.getHeader("token")); AuthContextUtil.setUserInfo(JSON.parseObject(userInfoJSON, UserInfo.class)); return true; } -} +} \ No newline at end of file diff --git a/spzx-server-gateway/src/main/java/cn/bunny/getway/config/RedisConfig.java b/spzx-server-gateway/src/main/java/cn/bunny/getway/config/RedisConfig.java new file mode 100644 index 0000000..5c822c2 --- /dev/null +++ b/spzx-server-gateway/src/main/java/cn/bunny/getway/config/RedisConfig.java @@ -0,0 +1,32 @@ +package cn.bunny.getway.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +public class RedisConfig { + + @Bean + @Primary + public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(redisConnectionFactory); + + // String的序列化方式 + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); + + // 序列号key value + redisTemplate.setKeySerializer(stringRedisSerializer); + redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer); + + redisTemplate.afterPropertiesSet(); + return redisTemplate; + } +} + diff --git a/spzx-server-gateway/src/main/java/cn/bunny/getway/filter/AuthGlobalFilter.java b/spzx-server-gateway/src/main/java/cn/bunny/getway/filter/AuthGlobalFilter.java index 274d5a3..c7dd9b3 100644 --- a/spzx-server-gateway/src/main/java/cn/bunny/getway/filter/AuthGlobalFilter.java +++ b/spzx-server-gateway/src/main/java/cn/bunny/getway/filter/AuthGlobalFilter.java @@ -26,21 +26,20 @@ import java.util.List; @Slf4j @Component public class AuthGlobalFilter implements GlobalFilter, Ordered { + + private final AntPathMatcher antPathMatcher = new AntPathMatcher(); @Resource - private RedisTemplate redisTemplate; - private AntPathMatcher antPathMatcher; + private RedisTemplate redisTemplate; @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - // 获取当前请求路径 ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getPath(); + UserInfo userInfo = this.getUserInfo(request); - // 判断路径是否满足 /api/**/auth/** + // api接口,异步请求,校验用户必须登录 if (antPathMatcher.match("/api/**/auth/**", path)) { - // 登录校验 - UserInfo userInfo = this.getUserinfo(request); - if (userInfo == null) { + if (null == userInfo) { ServerHttpResponse response = exchange.getResponse(); return out(response, ResultCodeEnum.LOGIN_AUTH); } @@ -54,26 +53,6 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { return 0; } - - private UserInfo getUserinfo(ServerHttpRequest request) { - String token = ""; - List tokenList = request.getHeaders().get("token"); - if (tokenList != null) { - token = tokenList.get(0); - } - if (StringUtils.hasText(token)) { - String userJson = (String) redisTemplate.opsForValue().get("user:spzx" + token); - - if (StringUtils.hasText(userJson)) { - return null; - } else { - return JSON.parseObject(userJson, UserInfo.class); - } - } - - return null; - } - private Mono out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) { Result result = Result.build(null, resultCodeEnum); byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8); @@ -82,4 +61,21 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); return response.writeWith(Mono.just(buffer)); } -} + + private UserInfo getUserInfo(ServerHttpRequest request) { + String token = ""; + List tokenList = request.getHeaders().get("token"); + if (null != tokenList) { + token = tokenList.get(0); + } + if (!StringUtils.isEmpty(token)) { + String userInfoJSON = redisTemplate.opsForValue().get("user:spzx:" + token); + if (StringUtils.isEmpty(userInfoJSON)) { + return null; + } else { + return JSON.parseObject(userInfoJSON, UserInfo.class); + } + } + return null; + } +} \ No newline at end of file diff --git a/spzx-server-gateway/src/main/resources/application-dev.yml b/spzx-server-gateway/src/main/resources/application-dev.yml index 7e91eea..1be62cd 100644 --- a/spzx-server-gateway/src/main/resources/application-dev.yml +++ b/spzx-server-gateway/src/main/resources/application-dev.yml @@ -7,6 +7,7 @@ spring: nacos: discovery: server-addr: 192.168.2.82:8848 + # server-addr: 192.168.31.202:8848 gateway: discovery: locator: @@ -40,7 +41,8 @@ spring: data: redis: host: 192.168.2.82 + # host: 192.168.31.202 port: 6379 mybatis: config-location: classpath:mybatis-config.xml - mapper-locations: classpath:/mapper/*/*.xml \ No newline at end of file + mapper-locations: classpath:/mapper/*/*.xml diff --git a/spzx-service/service-cart/pom.xml b/spzx-service/service-cart/pom.xml index a628ca0..8d50c9c 100644 --- a/spzx-service/service-cart/pom.xml +++ b/spzx-service/service-cart/pom.xml @@ -1,4 +1,4 @@ - 4.0.0 @@ -25,5 +25,9 @@ 3.8.1 test + + org.springframework.boot + spring-boot-starter-data-redis + diff --git a/spzx-service/service-cart/src/main/java/cn/bunny/web/controller/CartController.java b/spzx-service/service-cart/src/main/java/cn/bunny/web/controller/CartController.java new file mode 100644 index 0000000..e79de8f --- /dev/null +++ b/spzx-service/service-cart/src/main/java/cn/bunny/web/controller/CartController.java @@ -0,0 +1,27 @@ +package cn.bunny.web.controller; + +import cn.bunny.common.spzx.model.vo.common.Result; +import cn.bunny.common.spzx.model.vo.common.ResultCodeEnum; +import cn.bunny.web.service.CartService; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.annotation.Resource; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("api/order/cart") +public class CartController { + + @Resource + private CartService cartService; + + @Operation(summary = "添加购物车") + @GetMapping("auth/addToCart/{skuId}/{skuNum}") + public Result addToCart(@PathVariable Long skuId, + @PathVariable Integer skuNum) { + cartService.addToCart(skuId, skuNum); + return Result.build(null, ResultCodeEnum.SUCCESS); + } +} diff --git a/spzx-service/service-cart/src/main/java/cn/bunny/web/service/CartService.java b/spzx-service/service-cart/src/main/java/cn/bunny/web/service/CartService.java new file mode 100644 index 0000000..fc8c433 --- /dev/null +++ b/spzx-service/service-cart/src/main/java/cn/bunny/web/service/CartService.java @@ -0,0 +1,6 @@ +package cn.bunny.web.service; + +public interface CartService { + // 添加购物车 + void addToCart(Long skuId, Integer skuNum); +} diff --git a/spzx-service/service-cart/src/main/java/cn/bunny/web/service/impl/CartServiceImpl.java b/spzx-service/service-cart/src/main/java/cn/bunny/web/service/impl/CartServiceImpl.java new file mode 100644 index 0000000..23e9c76 --- /dev/null +++ b/spzx-service/service-cart/src/main/java/cn/bunny/web/service/impl/CartServiceImpl.java @@ -0,0 +1,63 @@ +package cn.bunny.web.service.impl; + +import cn.bunny.common.AuthContextUtil; +import cn.bunny.common.spzx.model.entity.h5.CartInfo; +import cn.bunny.common.spzx.model.entity.product.ProductSku; +import cn.bunny.web.service.CartService; +import com.alibaba.fastjson.JSON; +import jakarta.annotation.Resource; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.Date; + +@Service +public class CartServiceImpl implements CartService { + @Resource + private RedisTemplate redisTemplate; + + // 定义key user:cart:userId + private String getCartKey(Long userId) { + return "user:cart:" + userId; + } + + // 添加购物车 + @Override + public void addToCart(Long skuId, Integer skuNum) { + // 1.必须是登录状态,获取当前登录用户id,从ThreadLocal获取用户信息就可以了 + Long userId = AuthContextUtil.getUserInfo().getId(); + String cartKey = this.getCartKey(userId); + + // 2.因为购物车放到Redis里面,从Redis里面获取购物车数据,根据key值 + skuId获取(hash类型key+field) + // hash类型 key:useId fileId:skuId value:sku信息CartInfo + Object cartInfoObj = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId)); + + // 3.如果购物车存在添加商品,把商品数量相加 + CartInfo cartInfo = null; + if (cartInfoObj != null) { + cartInfo = JSON.parseObject(cartInfoObj.toString(), CartInfo.class); + // 数量相加 + cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum); + // 购物车商品是选中状态 + cartInfo.setIsChecked(1); + cartInfo.setUpdateTime(new Date()); + } else { + // 4.如果购物车没有商品,直接商品添加购物车(添加到Redis里面) + // 远程调用实现:通过nacos + openFeign 实现,根据skuId获取商品sku信息 + cartInfo = new CartInfo(); + // 远程调用实现:根据skuId获取商品sku信息 + ProductSku productSku = null; + cartInfo.setCartPrice(productSku.getSalePrice()); + cartInfo.setSkuNum(skuNum); + cartInfo.setSkuId(skuId); + cartInfo.setUserId(userId); + cartInfo.setImgUrl(productSku.getThumbImg()); + cartInfo.setSkuName(productSku.getSkuName()); + cartInfo.setIsChecked(1); + cartInfo.setCreateTime(new Date()); + cartInfo.setUpdateTime(new Date()); + } + + redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo)); + } +} diff --git a/spzx-service/service-cart/src/main/resources/application-dev.yml b/spzx-service/service-cart/src/main/resources/application-dev.yml index dfd538b..b79e153 100644 --- a/spzx-service/service-cart/src/main/resources/application-dev.yml +++ b/spzx-service/service-cart/src/main/resources/application-dev.yml @@ -11,4 +11,8 @@ spring: data: redis: host: 192.168.2.82 - port: 6379 \ No newline at end of file + # host: 192.168.31.202 + port: 6379 + mvc: + pathmatch: + matching-strategy: ant_path_matcher \ No newline at end of file diff --git a/spzx-service/service-product/src/main/resources/application-dev.yml b/spzx-service/service-product/src/main/resources/application-dev.yml index 0859a39..daa802e 100644 --- a/spzx-service/service-product/src/main/resources/application-dev.yml +++ b/spzx-service/service-product/src/main/resources/application-dev.yml @@ -8,6 +8,7 @@ spring: nacos: discovery: server-addr: 192.168.2.82:8848 + # server-addr: 192.168.31.202:8848 datasource: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver @@ -18,6 +19,7 @@ spring: redis: port: 6379 host: 192.168.2.82 +# host: 192.168.31.202 mybatis: config-location: classpath:mybatis-config.xml diff --git a/spzx-service/service-user/src/main/java/cn/bunny/user/User.java b/spzx-service/service-user/src/main/java/cn/bunny/user/User.java index f9d0597..fe890bb 100644 --- a/spzx-service/service-user/src/main/java/cn/bunny/user/User.java +++ b/spzx-service/service-user/src/main/java/cn/bunny/user/User.java @@ -1,13 +1,13 @@ package cn.bunny.user; -import cn.bunny.anno.EnableUserLoginAuthInterceptor; +import cn.bunny.anno.EnableUserWebMvcConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"cn.bunny"}) -@EnableUserLoginAuthInterceptor +@EnableUserWebMvcConfiguration public class User { public static void main(String[] args) { SpringApplication.run(User.class, args); diff --git a/spzx-service/service-user/src/main/java/cn/bunny/user/controller/UserinfoController.java b/spzx-service/service-user/src/main/java/cn/bunny/user/controller/UserinfoController.java index 128acc7..9947c81 100644 --- a/spzx-service/service-user/src/main/java/cn/bunny/user/controller/UserinfoController.java +++ b/spzx-service/service-user/src/main/java/cn/bunny/user/controller/UserinfoController.java @@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.*; @Tag(name = "会员用户接口") @RestController -@RequestMapping("api/user/userInfo") +@RequestMapping("/api/user/userInfo") public class UserinfoController { @Resource private UserinfoService userinfoService; diff --git a/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java b/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java index 01d33c8..4305c08 100644 --- a/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java +++ b/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java @@ -1,5 +1,6 @@ package cn.bunny.user.service.impl; +import cn.bunny.common.AuthContextUtil; import cn.bunny.common.exception.BunnyException; import cn.bunny.common.spzx.model.dto.h5.UserLoginDto; import cn.bunny.common.spzx.model.dto.h5.UserRegisterDto; @@ -14,7 +15,6 @@ import org.springframework.beans.BeanUtils; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; -import org.springframework.util.StringUtils; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -29,7 +29,7 @@ public class UserinfoServiceImpl implements UserinfoService { // 获取当前登录用户信息 @Override public UserInfoVo getCurrentUserInfo(String token) { - // 从Redis根据token获取用户信息 +/* // 从Redis根据token获取用户信息 String userJson = (String) redisTemplate.opsForValue().get("user:spzx" + token); if (!StringUtils.hasText(userJson)) { throw new BunnyException(ResultCodeEnum.LOGIN_ERROR); @@ -40,6 +40,10 @@ public class UserinfoServiceImpl implements UserinfoService { UserInfoVo userInfoVo = new UserInfoVo(); BeanUtils.copyProperties(userinfo, userInfoVo); + return userInfoVo; */ + UserInfo userInfo = AuthContextUtil.getUserInfo(); + UserInfoVo userInfoVo = new UserInfoVo(); + BeanUtils.copyProperties(userInfo, userInfoVo); return userInfoVo; } diff --git a/spzx-service/service-user/src/main/resources/application-dev.yml b/spzx-service/service-user/src/main/resources/application-dev.yml index d8e9a74..158c340 100644 --- a/spzx-service/service-user/src/main/resources/application-dev.yml +++ b/spzx-service/service-user/src/main/resources/application-dev.yml @@ -8,6 +8,7 @@ spring: nacos: discovery: server-addr: 192.168.2.82:8848 + # server-addr: 192.168.31.202:8848 datasource: @@ -20,6 +21,7 @@ spring: redis: port: 6379 host: 192.168.2.82 +# host: 192.168.31.202 mybatis: config-location: classpath:mybatis-config.xml