feat(修复): 远程调用问题,修改Redis地址,全局拦截器更改

Signed-off-by: bunny <1319900154@qq.com>
This commit is contained in:
bunny 2024-03-28 19:47:21 +08:00
parent dc86482af3
commit 579365293c
19 changed files with 120 additions and 67 deletions

View File

@ -14,12 +14,12 @@
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="2@106.15.251.123" uuid="7948c4f2-c26d-4886-b6da-d40f6a617678">
<data-source source="LOCAL" name="2@47.120.65.66" uuid="7948c4f2-c26d-4886-b6da-d40f6a617678">
<driver-ref>redis</driver-ref>
<synchronize>true</synchronize>
<imported>true</imported>
<jdbc-driver>jdbc.RedisDriver</jdbc-driver>
<jdbc-url>jdbc:redis://106.15.251.123:6379/2</jdbc-url>
<jdbc-url>jdbc:redis://47.120.65.66:6379/2</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />

View File

@ -39,11 +39,12 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
log.info("WebMvcConfiguration===>开始注册自定义拦截器...");
// 拦截后台管理内容
String[] loginAuthInterceptors = {"/admin/system/index/login", "/admin/system/index/generateValidateCode", "/admin/product/category/exportData"};
// 需要拦截的
registry.addInterceptor(loginAuthInterceptor).addPathPatterns("/admin/**")
.excludePathPatterns(loginAuthInterceptors);
registry.addInterceptor(userLoginAuthInterceptor).addPathPatterns("/api/**/auth/**");
// 拦截前台内容
registry.addInterceptor(userLoginAuthInterceptor).addPathPatterns("/api/**");
}
}

View File

@ -1,19 +1,19 @@
package com.atguigu.interceptor;
import com.alibaba.fastjson.JSON;
import com.atguigu.constant.MessageConstant;
import com.atguigu.context.BaseContext;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.utils.EmptyUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Configuration
@Slf4j
@ -24,25 +24,19 @@ public class UserLoginAuthInterceptor implements HandlerInterceptor {
private EmptyUtil emptyUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("UserLoginAuthInterceptor===>preHandle拦截请求前");
// 判断token是否为空
public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
String token = request.getHeader("token");
emptyUtil.isEmpty(token, MessageConstant.TOKEN_IS_EMPTY);
Object userJSON = redisTemplate.opsForValue().get(token);
String jsonString = JSON.toJSONString(userJSON);
BaseContext.setUserInfo(JSON.parseObject(jsonString, UserInfo.class));
if (!StringUtils.isEmpty(token)) {
Object userJSON = redisTemplate.opsForValue().get(token);
String userJSONString = JSON.toJSONString(userJSON);
BaseContext.setUserInfo(JSON.parseObject(userJSONString, UserInfo.class));
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) throws Exception {
BaseContext.removeUserInfo();
}
}

View File

@ -0,0 +1,38 @@
package com.atguigu.utils;
import com.alibaba.fastjson.JSON;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisUserConstant;
import com.atguigu.exception.BunnyException;
import com.atguigu.spzx.model.entity.user.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public static String getCartKey(Long userId) {
return RedisUserConstant.REDIS_CART_KEY + userId;
}
/**
* Redis通过token获取用户信息
*
* @param token 请求key的token
* @return 用户信息
*/
public UserInfo getUserInfo(String token) {
// 获取用户信息字符串
Object object = redisTemplate.opsForValue().get(token);
String jsonString = JSON.toJSONString(object);
if (StringUtils.isEmpty(jsonString)) {
throw new BunnyException(MessageConstant.USER_DOES_NOT_EXIST);
}
// 转为UserInfo类
return JSON.parseObject(jsonString, UserInfo.class);
}
}

View File

@ -0,0 +1,11 @@
package com.atguigu.constant;
import lombok.Data;
/**
* Redis用户前缀设置
*/
@Data
public class RedisUserConstant {
public static final String REDIS_CART_KEY = "cart::";
}

View File

@ -7,9 +7,10 @@ bunny:
password: "02120212"
redis:
host: 106.15.251.123
host: 47.120.65.66
port: 6379
database: 2
password: "02120212"
minio:
endpointUrl: "http://129.211.31.58:9000"

View File

@ -20,6 +20,7 @@ spring:
host: ${bunny.redis.host}
port: ${bunny.redis.port}
database: ${bunny.redis.database}
password: ${bunny.redis.password}
logging:
level:

View File

@ -3,65 +3,47 @@ package com.atguigu.gateway.filter;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.model.vo.result.Result;
import com.atguigu.spzx.model.vo.result.ResultCodeEnum;
import com.atguigu.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private RedisUtils redisUtils;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取请求路径
// 当前请求路径
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
// 判断路径 /api/**/auth/**登录校验
if (antPathMatcher.match("/api/**/auth/**", path)) {
// 登录校验
Object userInfo = getUserInfo(request);
String token = request.getHeaders().get("token").get(0);
Object userInfo = redisUtils.getUserInfo(token);
if (userInfo == null) {
ServerHttpResponse response = exchange.getResponse();
return out(response, ResultCodeEnum.LOGIN_AUTH);
}
}
// 放行
return chain.filter(exchange);
}
private Object getUserInfo(ServerHttpRequest request) {
// 从请求头获取token
String token = "";
List<String> tokenList = request.getHeaders().get("token");
if (tokenList != null) {
token = tokenList.get(0);
}
// 判断token是否为空
if (!StringUtils.isEmpty(token)) {
// 根据token查询redis
return redisTemplate.opsForValue().get(token);
}
return null;
}
@Override
public int getOrder() {
return 0;

View File

@ -5,6 +5,7 @@ bunny:
namespace: spzx
redis:
host: 106.15.251.123
host: 47.120.65.66
port: 6379
database: 2
database: 2
password: "02120212"

View File

@ -10,14 +10,14 @@ spring:
# allow-bean-definition-overriding: true
cloud:
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
nacos:
discovery:
namespace: ${bunny.nacos.discovery.namespace}
server-addr: ${bunny.nacos.server-addr}
log-name: logs/${spring.application.name}
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
gateway:
discovery:
locator:
@ -56,6 +56,7 @@ spring:
host: ${bunny.redis.host}
port: ${bunny.redis.port}
database: ${bunny.redis.database}
password: ${bunny.redis.password}
logging:
level:

View File

@ -6,7 +6,7 @@ import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name = "service-product")
@FeignClient(name = "service-product", path = "/api/product/")
public interface ProductFeignClient {
@GetMapping("getBySkuId/{skuId}")
Result<ProductSku> getBySkuId(@PathVariable Long skuId);

View File

@ -7,6 +7,7 @@ import com.atguigu.context.BaseContext;
import com.atguigu.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.h5.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@ -32,14 +33,15 @@ public class CartServiceImpl implements CartService {
*/
@Override
public void addToCart(Long skuId, Integer skuNum) {
// 当前用户
Long userId = BaseContext.getUserInfo().getId();
// 获取key名称
String cartKey = userId.toString();
// 用户id组合得到购物车id
String cartKey = RedisUtils.getCartKey(userId);
Object cartInfoJson = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));
// 如果不为空
CartInfo cartInfo = null;
if (cartInfoJson != null) {
cartInfo = JSON.parseObject(cartInfoJson.toString(), CartInfo.class);
cartInfo = JSON.parseObject(JSON.toJSONString(cartInfoJson), CartInfo.class);
// 数量相加
cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
// 购物车状态为选中
@ -61,7 +63,7 @@ public class CartServiceImpl implements CartService {
cartInfo.setUpdateTime(new Date());
}
// 将商品数据存储到购物车中
redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo));
redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), cartInfo);
}
/**
@ -73,13 +75,13 @@ public class CartServiceImpl implements CartService {
public List<CartInfo> getCartList() {
// 获取当前登录的用户信息
Long userId = BaseContext.getUserInfo().getId();
String cartKey = userId.toString();
String cartKey = RedisUtils.getCartKey(userId);
// 获取数据
List<Object> cartInfoList = redisTemplate.opsForHash().values(cartKey);
if (!CollectionUtils.isEmpty(cartInfoList)) {
return cartInfoList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
return cartInfoList.stream().map(cartInfoJSON -> JSON.parseObject(JSON.toJSONString(cartInfoJSON), CartInfo.class))
.sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
.collect(Collectors.toList());
}
@ -96,7 +98,7 @@ public class CartServiceImpl implements CartService {
public void deleteCart(Long skuId) {
// 获取当前登录的用户数据
Long userId = BaseContext.getUserInfo().getId();
String cartKey = userId.toString();
String cartKey = RedisUtils.getCartKey(userId);
// 获取缓存对象
redisTemplate.opsForHash().delete(cartKey, String.valueOf(skuId));
@ -112,14 +114,15 @@ public class CartServiceImpl implements CartService {
public void checkCart(Long skuId, Integer isChecked) {
// 获取当前登录的用户数据
Long userId = BaseContext.getUserInfo().getId();
String cartKey = userId.toString();
String cartKey = RedisUtils.getCartKey(userId);
Boolean hasKey = redisTemplate.opsForHash().hasKey(cartKey, String.valueOf(skuId));
if (hasKey) {
String cartInfoJSON = Objects.requireNonNull(redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId))).toString();
Object cartInfoString = Objects.requireNonNull(redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId)));
String cartInfoJSON = JSON.toJSONString(cartInfoString);
CartInfo cartInfo = JSON.parseObject(cartInfoJSON, CartInfo.class);
cartInfo.setIsChecked(isChecked);
redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), JSON.toJSONString(cartInfo));
redisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), cartInfo);
}
}
@ -132,16 +135,16 @@ public class CartServiceImpl implements CartService {
public void allCheckCart(Integer isChecked) {
// 获取当前登录的用户数据
Long userId = BaseContext.getUserInfo().getId();
String cartKey = userId.toString();
String cartKey = RedisUtils.getCartKey(userId);
// 获取所有的购物项数据
List<Object> objectList = redisTemplate.opsForHash().values(cartKey);
if (!CollectionUtils.isEmpty(objectList)) {
objectList.stream().map(cartInfoJSON -> {
CartInfo cartInfo = JSON.parseObject(cartInfoJSON.toString(), CartInfo.class);
CartInfo cartInfo = JSON.parseObject(JSON.toJSONString(cartInfoJSON), CartInfo.class);
cartInfo.setIsChecked(isChecked);
return cartInfo;
}).forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey, String.valueOf(cartInfo.getSkuId()), JSON.toJSONString(cartInfo)));
}).forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey, String.valueOf(cartInfo.getSkuId()), cartInfo));
}
}
@ -151,7 +154,7 @@ public class CartServiceImpl implements CartService {
@Override
public void clearCart() {
Long userId = BaseContext.getUserInfo().getId();
String cartKey = userId.toString();
String cartKey = RedisUtils.getCartKey(userId);
redisTemplate.delete(cartKey);
}
}

View File

@ -1,8 +1,9 @@
bunny:
redis:
host: 106.15.251.123
host: 47.120.65.66
port: 6379
database: 2
password: "02120212"
nacos:
server-addr: z-bunny.cn:8848

View File

@ -7,6 +7,9 @@ spring:
name: service-cart
cloud:
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
nacos:
discovery:
namespace: ${bunny.nacos.discovery.namespace}
@ -17,6 +20,7 @@ spring:
host: ${bunny.redis.host}
port: ${bunny.redis.port}
database: ${bunny.redis.database}
password: ${bunny.redis.password}
logging:
level:

View File

@ -7,8 +7,13 @@ spring:
name: service-order
cloud:
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
nacos:
server-addr: 192.168.1.5:8848
discovery:
namespace: ${bunny.nacos.discovery.namespace}
server-addr: ${bunny.nacos.server-addr}
datasource:
type: com.zaxxer.hikari.HikariDataSource

View File

@ -7,9 +7,10 @@ bunny:
password: "02120212"
redis:
host: 106.15.251.123
host: 47.120.65.66
port: 6379
database: 2
password: "02120212"
nacos:
server-addr: z-bunny.cn:8848

View File

@ -8,6 +8,9 @@ spring:
main:
allow-bean-definition-overriding: true
cloud:
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
nacos:
discovery:
namespace: ${bunny.nacos.discovery.namespace}
@ -25,6 +28,7 @@ spring:
host: ${bunny.redis.host}
port: ${bunny.redis.port}
database: ${bunny.redis.database}
password: ${bunny.redis.password}
logging:
level:

View File

@ -7,9 +7,10 @@ bunny:
password: "02120212"
redis:
host: 106.15.251.123
host: 47.120.65.66
port: 6379
database: 2
password: "02120212"
nacos:
server-addr: z-bunny.cn:8848

View File

@ -7,6 +7,9 @@ spring:
name: service-user
cloud:
sentinel:
log:
dir: logs/${spring.application.name}/sentinel
nacos:
discovery:
namespace: ${bunny.nacos.discovery.namespace}
@ -24,6 +27,7 @@ spring:
host: ${bunny.redis.host}
port: ${bunny.redis.port}
database: ${bunny.redis.database}
password: ${bunny.redis.password}
logging:
level: