Browse Source

新增租户初始化切面事件

zyh
Loki 3 years ago
parent
commit
49c3e34b23
  1. 12
      yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/context/TenantContextHolder.java
  2. 9
      yudao-module-system/yudao-module-system-impl/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java
  3. 2
      yudao-ui-admin
  4. 21
      zsw-bxg/src/main/java/co/yixiang/app/modules/auth/rest/LetterAppAuthController.java
  5. 2
      zsw-bxg/src/main/java/co/yixiang/app/modules/services/AppAuthService.java
  6. 2
      zsw-bxg/src/main/java/co/yixiang/app/modules/services/CreatShareProductService.java
  7. 8
      zsw-bxg/src/main/java/co/yixiang/app/modules/wechat/rest/controller/WxMaUserController.java
  8. 55
      zsw-bxg/src/main/java/co/yixiang/aspect/TenantInitAspect.java
  9. 97
      zsw-bxg/src/main/java/co/yixiang/listener/RedisKeyInitialization.java
  10. 2
      zsw-bxg/src/main/java/co/yixiang/modules/activity/service/impl/YxStoreCombinationServiceImpl.java
  11. 2
      zsw-bxg/src/main/java/co/yixiang/modules/activity/service/impl/YxStoreSeckillServiceImpl.java
  12. 2
      zsw-bxg/src/main/java/co/yixiang/modules/customer/rest/QrCodeController.java
  13. 449
      zsw-bxg/src/main/java/co/yixiang/utils/RedisUtils.java
  14. 55
      zsw-bxg/src/main/java/co/yixiang/utils/ShopKeyUtils.java

12
yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/context/TenantContextHolder.java

@ -2,6 +2,8 @@ package cn.iocoder.yudao.framework.tenant.core.context;
import com.alibaba.ttl.TransmittableThreadLocal; import com.alibaba.ttl.TransmittableThreadLocal;
import java.util.function.Supplier;
/** /**
* 多租户上下文 Holder * 多租户上下文 Holder
* *
@ -58,6 +60,16 @@ public class TenantContextHolder {
return Boolean.TRUE.equals(IGNORE.get()); return Boolean.TRUE.equals(IGNORE.get());
} }
public static <T> T apply(Long tenantId, Supplier<T> func){
Long oldTenant = TenantContextHolder.getTenantId();
try {
TenantContextHolder.setTenantId(tenantId);
return func.get();
}finally {
TenantContextHolder.setTenantId(oldTenant);
}
}
public static void clear() { public static void clear() {
TENANT_ID.remove(); TENANT_ID.remove();
IGNORE.remove(); IGNORE.remove();

9
yudao-module-system/yudao-module-system-impl/src/main/java/cn/iocoder/yudao/module/system/service/auth/AdminAuthServiceImpl.java

@ -1,5 +1,6 @@
package cn.iocoder.yudao.module.system.service.auth; package cn.iocoder.yudao.module.system.service.auth;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
@ -13,6 +14,7 @@ import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialBi
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialLogin2ReqVO; import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialLogin2ReqVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialLoginReqVO; import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialLoginReqVO;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert; import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.CpUser.CpUserDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum; import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum; import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
@ -113,8 +115,11 @@ public class AdminAuthServiceImpl implements AdminAuthService {
// 使用账号密码,进行登录 // 使用账号密码,进行登录
LoginUser loginUser = this.login0(reqVO.getUsername(), reqVO.getPassword()); LoginUser loginUser = this.login0(reqVO.getUsername(), reqVO.getPassword());
//将cpUserId存入 key为 系统用户id value为 cpUserId CpUserDO wxUser = cpUserService.getByUserId(loginUser.getUsername());
redisTemplate.opsForValue().set("CpUserId::" + loginUser.getId(), cpUserService.getByUserId(loginUser.getUsername()).getId().toString()); if (ObjectUtil.isNotEmpty(wxUser)){
//将cpUserId存入 key为 系统用户id value为 cpUserId
redisTemplate.opsForValue().set("CpUserId::" + loginUser.getId(), wxUser.getId().toString());
}
// 缓存登陆用户到 Redis 中,返回 sessionId 编号 // 缓存登陆用户到 Redis 中,返回 sessionId 编号
return createUserSessionAfterLoginSuccess(loginUser, LoginLogTypeEnum.LOGIN_USERNAME, userIp, userAgent); return createUserSessionAfterLoginSuccess(loginUser, LoginLogTypeEnum.LOGIN_USERNAME, userIp, userAgent);

2
yudao-ui-admin

@ -1 +1 @@
Subproject commit beb44f8aa54a4e20a48985d771a0353641df4787 Subproject commit e2285febb83a51499ae0ae28fd89b8f301913c51

21
zsw-bxg/src/main/java/co/yixiang/app/modules/auth/rest/LetterAppAuthController.java

@ -106,7 +106,7 @@ public class LetterAppAuthController {
@ApiOperation(value = "小程序获取用户信息", notes = "小程序获取用户信息") @ApiOperation(value = "小程序获取用户信息", notes = "小程序获取用户信息")
public ApiResult<YxUser> loginAuth(@Validated @RequestBody LoginParam loginParam) { public ApiResult<YxUser> loginAuth(@Validated @RequestBody LoginParam loginParam) {
Long uid = LocalUser.getUidByToken(); Long uid = LocalUser.getUidByToken();
String sessionKey = redisUtil.get(ShopConstants.ZSW_MINI_SESSION_KET + uid).toString(); String sessionKey = redisUtil.getY(ShopConstants.ZSW_MINI_SESSION_KET + uid);
YxUser yxUser = authService.loginAuth(loginParam, uid, sessionKey); YxUser yxUser = authService.loginAuth(loginParam, uid, sessionKey);
return ApiResult.ok(yxUser).setMsg("获取成功"); return ApiResult.ok(yxUser).setMsg("获取成功");
@ -181,11 +181,10 @@ public class LetterAppAuthController {
@ApiOperation("H5验证码登录授权") @ApiOperation("H5验证码登录授权")
@PostMapping(value = "/login/mobile") @PostMapping(value = "/login/mobile")
public ApiResult<Map<String, Object>> loginVerify(@Validated @RequestBody LoginVerifyParam loginVerifyParam, HttpServletRequest request) { public ApiResult<Map<String, Object>> loginVerify(@Validated @RequestBody LoginVerifyParam loginVerifyParam, HttpServletRequest request) {
Object codeObj = redisUtil.get("code_" + loginVerifyParam.getAccount()); String code = redisUtil.getY("code_" + loginVerifyParam.getAccount());
if(codeObj == null){ if(code == null){
throw new YshopException("请先获取验证码"); throw new YshopException("请先获取验证码");
} }
String code = codeObj.toString();
if (!StrUtil.equals(code, loginVerifyParam.getCaptcha())) { if (!StrUtil.equals(code, loginVerifyParam.getCaptcha())) {
throw new YshopException("验证码错误"); throw new YshopException("验证码错误");
} }
@ -221,11 +220,10 @@ public class LetterAppAuthController {
@ApiOperation("修改密码") @ApiOperation("修改密码")
@PostMapping(value = "/register/reset") @PostMapping(value = "/register/reset")
public ApiResult<Boolean> updatePassword(@Validated @RequestBody UpdatePasswordParam updatePasswordParam, HttpServletRequest request) { public ApiResult<Boolean> updatePassword(@Validated @RequestBody UpdatePasswordParam updatePasswordParam, HttpServletRequest request) {
Object codeObj = redisUtil.get("code_" + updatePasswordParam.getAccount()); String code = redisUtil.getY("code_" + updatePasswordParam.getAccount());
if(codeObj == null){ if(code == null){
throw new YshopException("请先获取验证码"); throw new YshopException("请先获取验证码");
} }
String code = codeObj.toString();
if (!StrUtil.equals(code, updatePasswordParam.getCaptcha())) { if (!StrUtil.equals(code, updatePasswordParam.getCaptcha())) {
throw new YshopException("验证码错误"); throw new YshopException("验证码错误");
} }
@ -252,11 +250,10 @@ public class LetterAppAuthController {
@PostMapping("/register") @PostMapping("/register")
@ApiOperation(value = "H5/APP注册新用户", notes = "H5/APP注册新用户") @ApiOperation(value = "H5/APP注册新用户", notes = "H5/APP注册新用户")
public ApiResult<String> register(@Validated @RequestBody RegParam param) { public ApiResult<String> register(@Validated @RequestBody RegParam param) {
Object codeObj = redisUtil.get("code_" + param.getAccount()); String code = redisUtil.getY("code_" + param.getAccount());
if(codeObj == null){ if(code == null){
return ApiResult.fail("请先获取验证码"); return ApiResult.fail("请先获取验证码");
} }
String code = codeObj.toString();
if (!StrUtil.equals(code, param.getCaptcha())) { if (!StrUtil.equals(code, param.getCaptcha())) {
return ApiResult.fail("验证码错误"); return ApiResult.fail("验证码错误");
} }
@ -283,8 +280,8 @@ public class LetterAppAuthController {
return ApiResult.fail("账号不存在"); return ApiResult.fail("账号不存在");
} }
String codeKey = "code_" + param.getPhone(); String codeKey = "code_" + param.getPhone();
if (ObjectUtil.isNotNull(redisUtil.get(codeKey))) { if (ObjectUtil.isNotNull(redisUtil.getY(codeKey))) {
return ApiResult.fail("10分钟内有效:" + redisUtil.get(codeKey).toString()); return ApiResult.fail("10分钟内有效:" + redisUtil.getY(codeKey));
} }
String code = RandomUtil.randomNumbers(ShopConstants.ZSW_SMS_SIZE); String code = RandomUtil.randomNumbers(ShopConstants.ZSW_SMS_SIZE);

2
zsw-bxg/src/main/java/co/yixiang/app/modules/services/AppAuthService.java

@ -328,7 +328,7 @@ public class AppAuthService {
* @param request / * @param request /
*/ */
public void save(YxUser yxUser, String token, HttpServletRequest request) { public void save(YxUser yxUser, String token, HttpServletRequest request) {
String job = "yshop开发工程师"; String job = "开发工程师";
String ip = StringUtils.getIp(request); String ip = StringUtils.getIp(request);
String browser = StringUtils.getBrowser(request); String browser = StringUtils.getBrowser(request);
String address = StringUtils.getCityInfo(ip); String address = StringUtils.getCityInfo(ip);

2
zsw-bxg/src/main/java/co/yixiang/app/modules/services/CreatShareProductService.java

@ -87,7 +87,7 @@ public class CreatShareProductService {
public YxStoreOrderQueryVo handleQrcode(YxStoreOrderQueryVo storeOrder,String path){ public YxStoreOrderQueryVo handleQrcode(YxStoreOrderQueryVo storeOrder,String path){
//门店 //门店
if(OrderInfoEnum.SHIPPIING_TYPE_2.getValue().equals(storeOrder.getShippingType())){ if(OrderInfoEnum.SHIPPIING_TYPE_2.getValue().equals(storeOrder.getShippingType())){
String mapKey = redisUtils.get(SystemConfigConstants.TENGXUN_MAP_KEY).toString(); String mapKey = redisUtils.getY(SystemConfigConstants.TENGXUN_MAP_KEY);
if(StrUtil.isBlank(mapKey)) { if(StrUtil.isBlank(mapKey)) {
throw new YshopException("请配置腾讯地图key"); throw new YshopException("请配置腾讯地图key");
} }

8
zsw-bxg/src/main/java/co/yixiang/app/modules/wechat/rest/controller/WxMaUserController.java

@ -54,12 +54,10 @@ public class WxMaUserController {
@PostMapping("/binding") @PostMapping("/binding")
@ApiOperation(value = "公众号绑定手机号", notes = "公众号绑定手机号") @ApiOperation(value = "公众号绑定手机号", notes = "公众号绑定手机号")
public ApiResult<String> verify(@Validated @RequestBody BindPhoneParam param) { public ApiResult<String> verify(@Validated @RequestBody BindPhoneParam param) {
Object codeObj = redisUtils.get("code_" + param.getPhone()); String code = redisUtils.getY("code_" + param.getPhone());
if(codeObj == null){ if(code == null){
return ApiResult.fail("请先获取验证码"); return ApiResult.fail("请先获取验证码");
} }
String code = codeObj.toString();
if (!StrUtil.equals(code, param.getCaptcha())) { if (!StrUtil.equals(code, param.getCaptcha())) {
return ApiResult.fail("验证码错误"); return ApiResult.fail("验证码错误");
} }
@ -94,7 +92,7 @@ public class WxMaUserController {
WxMaService wxMaService = WxMaConfiguration.getWxMaService(); WxMaService wxMaService = WxMaConfiguration.getWxMaService();
String phone = ""; String phone = "";
try { try {
String sessionKey = redisUtils.get(ShopConstants.ZSW_MINI_SESSION_KET + user.getUid()).toString(); String sessionKey = redisUtils.getY(ShopConstants.ZSW_MINI_SESSION_KET + user.getUid());
WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService() WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService()
.getPhoneNoInfo(sessionKey, param.getEncryptedData(), param.getIv()); .getPhoneNoInfo(sessionKey, param.getEncryptedData(), param.getIv());
phone = phoneNoInfo.getPhoneNumber(); phone = phoneNoInfo.getPhoneNumber();

55
zsw-bxg/src/main/java/co/yixiang/aspect/TenantInitAspect.java

@ -1,13 +1,28 @@
package co.yixiang.aspect; package co.yixiang.aspect;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import co.yixiang.modules.canvas.domain.StoreCanvas;
import co.yixiang.modules.canvas.service.StoreCanvasService;
import co.yixiang.modules.shop.domain.YxSystemConfig;
import co.yixiang.modules.shop.domain.YxSystemGroupData;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.shop.service.YxSystemGroupDataService;
import co.yixiang.tools.domain.QiniuConfig;
import co.yixiang.tools.service.QiniuConfigService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
/** /**
* 如果有新租户需要创建 则需要调用这个方法执行一些操作初始化一些数据 * 如果有新租户需要创建 则需要调用这个方法执行一些操作初始化一些数据
* 如动态图设计前端可以不用后端这个功能依然保持七牛初始化配置 * 如动态图设计前端可以不用后端这个功能依然保持七牛初始化配置
@ -16,14 +31,46 @@ import org.springframework.stereotype.Component;
@Aspect @Aspect
@Component @Component
@Slf4j @Slf4j
@Order
public class TenantInitAspect { public class TenantInitAspect {
@Autowired
private StoreCanvasService storeCanvasService;
@Autowired
private YxSystemGroupDataService systemGroupDataService;
@Autowired
private QiniuConfigService qiniuConfigService;
@Autowired
private YxSystemConfigService systemConfigService;
@Pointcut("execution(* cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper.insert(..))") @Pointcut("execution(* cn.iocoder.yudao.module.system.service.tenant.TenantService.createTenant(..))")
public void tenantInit(){} public void tenantInit(){}
@AfterReturning(value = "tenantInit()",returning = "tenant") @AfterReturning(value = "tenantInit()",returning = "tenantId")
public void afterTenantInit(JoinPoint point, TenantDO tenant){ public void afterTenantInit(JoinPoint point, Long tenantId){
log.info("新租户被加入,准备初始化...{}",tenant); log.info("新租户被加入,准备初始化...{}",tenantId);
// 动画
StoreCanvas temp = TenantContextHolder.apply(0L,()-> storeCanvasService.getById(1));
temp.setCanvasId(null);
temp.setCreateTime(new Date());
TenantContextHolder.apply(tenantId,()->storeCanvasService.save(temp));
//数据设置
List<YxSystemGroupData> list = TenantContextHolder.apply(0L, () -> systemGroupDataService.list());
list.forEach(yxSystemGroupData -> {
yxSystemGroupData.setCreateTime(new Date());
yxSystemGroupData.setId(null);
});
TenantContextHolder.apply(tenantId,()->systemGroupDataService.saveBatch(list));
//七牛设置
QiniuConfig qiniuConfig = TenantContextHolder.apply(0L, () -> qiniuConfigService.getById(1));
qiniuConfig.setId(null);
TenantContextHolder.apply(tenantId,()->qiniuConfigService.save(qiniuConfig));
//系统设置
List<YxSystemConfig> configs = TenantContextHolder.apply(0L,()->systemConfigService.list());
configs.forEach(config->{
config.setId(null);
});
TenantContextHolder.apply(tenantId,()->systemConfigService.saveBatch(configs));
} }
} }

97
zsw-bxg/src/main/java/co/yixiang/listener/RedisKeyInitialization.java

@ -1,97 +0,0 @@
package co.yixiang.listener;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import cn.iocoder.yudao.module.system.service.tenant.TenantServiceImpl;
import co.yixiang.modules.shop.domain.YxSystemConfig;
import co.yixiang.modules.shop.domain.YxSystemGroupData;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.shop.service.YxSystemGroupDataService;
import co.yixiang.modules.shop.service.dto.YxSystemGroupDataQueryCriteria;
import co.yixiang.utils.RedisUtils;
import com.google.common.collect.Lists;
import jodd.util.MapEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Component
public class RedisKeyInitialization implements CommandLineRunner {
@Resource
private TenantServiceImpl tenantService;
@Autowired
private RedisUtils redisUtils;
@Autowired
private YxSystemConfigService systemConfigService;
@Autowired
private YxSystemGroupDataService systemGroupDataService;
@Override
public void run(String... args) throws Exception {
Map<Long, TenantDO> tenantCache = tenantService.getTenantCache();
TenantContextHolder.setTenantId(0L);
// 配置模版
List<YxSystemConfig> configTemplateList = systemConfigService.queryAll(null);
// 商城数据
List<YxSystemGroupData> groupDataTemplateList = systemGroupDataService.queryAll(null);
for ( Map.Entry <Long,TenantDO> entry : tenantCache.entrySet()){
TenantDO tenant = entry.getValue();
TenantContextHolder.setTenantId(tenant.getId());
// 处理系统设置
List<YxSystemConfig> configs = systemConfigService.queryAll(null);
List<String> configsName = configs.stream()
.map(YxSystemConfig::getMenuName)
.collect(Collectors.toList());
// 准备配置模版 将已经有的剔除 没有的准备插入数据库
List<YxSystemConfig> rsT = ObjectUtil.clone(configTemplateList);
if (ObjectUtil.isNotEmpty(configsName)) {
rsT.removeIf(r -> configsName.contains(r.getMenuName()));
}
// 清除id
rsT.forEach(r-> r.setId(null));
systemConfigService.saveBatch(rsT);
// 处理系统配置
List<YxSystemGroupData> groupDatas = systemGroupDataService.queryAll(
new YxSystemGroupDataQueryCriteria().setStatus(1));
List<String> groupDatasNames = groupDatas.stream()
.map(YxSystemGroupData::getGroupName)
.collect(Collectors.toList());
List<YxSystemGroupData> rsD = ObjectUtil.clone(groupDataTemplateList);
if (ObjectUtil.isNotEmpty(groupDatasNames)) {
rsD.removeIf(r -> groupDatasNames.contains(r.getGroupName()));
}
rsD.forEach(r-> r.setId(null));
systemGroupDataService.saveBatch(rsD);
// 重新读取
configs = systemConfigService.queryAll(null);
for (YxSystemConfig config: configs) {
redisUtils.set(config.getMenuName(),config.getValue());
}
log.info("租户:{} 配置和缓存处理完成。。。",tenant.getName());
}
}
}

2
zsw-bxg/src/main/java/co/yixiang/modules/activity/service/impl/YxStoreCombinationServiceImpl.java

@ -140,7 +140,7 @@ public class YxStoreCombinationServiceImpl extends BaseServiceImpl<YxStoreCombin
storeCombinationVo.setReplyChance(replyService.replyPer(storeCombinationQueryVo.getProductId())); storeCombinationVo.setReplyChance(replyService.replyPer(storeCombinationQueryVo.getProductId()));
//获取运费模板名称 //获取运费模板名称
String storeFreePostage = redisUtils.get("store_free_postage").toString(); String storeFreePostage = redisUtils.getY("store_free_postage");
String tempName = ""; String tempName = "";
if(StrUtil.isBlank(storeFreePostage) if(StrUtil.isBlank(storeFreePostage)
|| !NumberUtil.isNumber(storeFreePostage) || !NumberUtil.isNumber(storeFreePostage)

2
zsw-bxg/src/main/java/co/yixiang/modules/activity/service/impl/YxStoreSeckillServiceImpl.java

@ -101,7 +101,7 @@ public class YxStoreSeckillServiceImpl extends BaseServiceImpl<YxStoreSeckillMap
//获取商品sku //获取商品sku
Map<String, Object> returnMap = yxStoreProductAttrService.getProductAttrDetail(storeSeckill.getProductId()); Map<String, Object> returnMap = yxStoreProductAttrService.getProductAttrDetail(storeSeckill.getProductId());
//获取运费模板名称 //获取运费模板名称
String storeFreePostage = redisUtils.get("store_free_postage").toString(); String storeFreePostage = redisUtils.getY("store_free_postage");
String tempName = ""; String tempName = "";
if(StrUtil.isBlank(storeFreePostage) if(StrUtil.isBlank(storeFreePostage)
|| !NumberUtil.isNumber(storeFreePostage) || !NumberUtil.isNumber(storeFreePostage)

2
zsw-bxg/src/main/java/co/yixiang/modules/customer/rest/QrCodeController.java

@ -103,7 +103,7 @@ public class QrCodeController {
@ResponseBody @ResponseBody
@GetMapping("/getOpenId") @GetMapping("/getOpenId")
public ResponseEntity userInfo(HttpServletRequest request, @RequestParam("key") String key) { public ResponseEntity userInfo(HttpServletRequest request, @RequestParam("key") String key) {
String openId = redisUtils.get("qrCode:" + key).toString(); String openId = redisUtils.getY("qrCode:" + key);
if (openId != null) { if (openId != null) {
String[] str = openId.split(":"); String[] str = openId.split(":");
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();

449
zsw-bxg/src/main/java/co/yixiang/utils/RedisUtils.java

@ -8,6 +8,9 @@
*/ */
package co.yixiang.utils; package co.yixiang.utils;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
@ -26,10 +29,14 @@ import java.util.concurrent.TimeUnit;
@SuppressWarnings({"unchecked","all"}) @SuppressWarnings({"unchecked","all"})
public class RedisUtils { public class RedisUtils {
@Autowired
private YxSystemConfigService systemConfigService;
@Resource @Resource
private RedisTemplate<String, Object> redisTemplate; private RedisTemplate<String, Object> redisTemplate;
private String buildCacheKey(String key){
return TenantContextHolder.getTenantId() + ":" + key;
}
// =============================commonold============================ // =============================commonold============================
@ -39,6 +46,7 @@ public class RedisUtils {
* @param time 时间() * @param time 时间()
*/ */
public boolean expire(String key, long time) { public boolean expire(String key, long time) {
key = buildCacheKey(key);
try { try {
if (time > 0) { if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS); redisTemplate.expire(key, time, TimeUnit.SECONDS);
@ -56,6 +64,7 @@ public class RedisUtils {
* @return 时间() 返回0代表为永久有效 * @return 时间() 返回0代表为永久有效
*/ */
public long getExpire(String key) { public long getExpire(String key) {
key = buildCacheKey(key);
return redisTemplate.getExpire(key, TimeUnit.SECONDS); return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} }
@ -65,6 +74,7 @@ public class RedisUtils {
* @return / * @return /
*/ */
public List<String> scan(String pattern) { public List<String> scan(String pattern) {
pattern = buildCacheKey(pattern);
ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection(); RedisConnection rc = Objects.requireNonNull(factory).getConnection();
@ -89,6 +99,7 @@ public class RedisUtils {
* @return / * @return /
*/ */
public List<String> findKeysForPage(String patternKey, int page, int size) { public List<String> findKeysForPage(String patternKey, int page, int size) {
patternKey = buildCacheKey(patternKey);
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection(); RedisConnection rc = Objects.requireNonNull(factory).getConnection();
@ -124,6 +135,7 @@ public class RedisUtils {
* @return true 存在 false不存在 * @return true 存在 false不存在
*/ */
public boolean hasKey(String key) { public boolean hasKey(String key) {
key = buildCacheKey(key);
try { try {
return redisTemplate.hasKey(key); return redisTemplate.hasKey(key);
} catch (Exception e) { } catch (Exception e) {
@ -137,6 +149,9 @@ public class RedisUtils {
* @param key 可以传一个值 或多个 * @param key 可以传一个值 或多个
*/ */
public void del(String... key) { public void del(String... key) {
Arrays.stream(key).forEach(s -> {
buildCacheKey(s);
});
if (key != null && key.length > 0) { if (key != null && key.length > 0) {
if (key.length == 1) { if (key.length == 1) {
redisTemplate.delete(key[0]); redisTemplate.delete(key[0]);
@ -154,22 +169,33 @@ public class RedisUtils {
* @return * @return
*/ */
public Object get(String key) { public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key); if (ObjectUtil.isEmpty(key)){
return null;
}
String tarKey = buildCacheKey(key);
Object rs = redisTemplate.opsForValue().get(tarKey);
if (ObjectUtil.isEmpty(rs)){
rs = systemConfigService.getData(key);
redisTemplate.opsForValue().set(tarKey,rs);
}
return rs;
} }
public String getY(String key){ public String getY(String key){
return key == null || !redisTemplate.hasKey(key) ? "" : redisTemplate.opsForValue().get(key).toString(); key = buildCacheKey(key);
if (ObjectUtil.isEmpty(key)){
return null;
}
String tarKey = buildCacheKey(key);
Object rs = redisTemplate.opsForValue().get(tarKey);
if (ObjectUtil.isEmpty(rs)){
rs = systemConfigService.getData(key);
redisTemplate.opsForValue().set(tarKey,rs);
}
return rs.toString();
} }
/**
* 批量获取
* @param keys
* @return
*/
public List<Object> multiGet(List<String> keys) {
Object obj = redisTemplate.opsForValue().multiGet(keys);
return null;
}
/** /**
* 普通缓存放入 * 普通缓存放入
@ -178,8 +204,9 @@ public class RedisUtils {
* @return true成功 false失败 * @return true成功 false失败
*/ */
public boolean set(String key, Object value) { public boolean set(String key, Object value) {
key = buildCacheKey(key);
try { try {
redisTemplate.opsForValue().set(key, value); redisTemplate.opsForValue().set(key,value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -195,6 +222,7 @@ public class RedisUtils {
* @return true成功 false 失败 * @return true成功 false 失败
*/ */
public boolean set(String key, Object value, long time) { public boolean set(String key, Object value, long time) {
key = buildCacheKey(key);
try { try {
if (time > 0) { if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
@ -217,6 +245,7 @@ public class RedisUtils {
* @return true成功 false 失败 * @return true成功 false 失败
*/ */
public boolean set(String key, String value, long time, TimeUnit timeUnit) { public boolean set(String key, String value, long time, TimeUnit timeUnit) {
key = buildCacheKey(key);
try { try {
if (time > 0) { if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, timeUnit); redisTemplate.opsForValue().set(key, value, time, timeUnit);
@ -229,398 +258,4 @@ public class RedisUtils {
return false; return false;
} }
} }
// ================================Map=================================
/**
* HashGet
* @param key 不能为null
* @param item 不能为null
* @return
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key
* @param map 对应多个键值
* @param time 时间()
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key
* @param item
* @param value
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key
* @param item
* @param value
* @param time 时间() 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 不能为null
* @param item 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 不能为null
* @param item 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key
* @param item
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key
* @param item
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key
* @param value
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key
* @param values 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key
* @param time 时间()
* @param values 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key
* @param values 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
* @param key
* @param start 开始
* @param end 结束 0 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key
* @param index 索引 index>=0时 0 表头1 第二个元素依次类推index<0时-1表尾-2倒数第二个元素依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key
* @param index 索引
* @param value
* @return /
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key
* @param count 移除多少个
* @param value
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
} }

55
zsw-bxg/src/main/java/co/yixiang/utils/ShopKeyUtils.java

@ -13,8 +13,7 @@ public class ShopKeyUtils {
*扩展值默认为空 把这个值追加到所有key值上 *扩展值默认为空 把这个值追加到所有key值上
*/ */
private static String getExtendValue(){ private static String getExtendValue(){
String extendValue= ""; return "";
return extendValue;
} }
//*********************************begin yx_system_config 通用值 ***************************************************** //*********************************begin yx_system_config 通用值 *****************************************************
@ -23,22 +22,19 @@ public class ShopKeyUtils {
* api_url * api_url
*/ */
public static String getApiUrl(){ public static String getApiUrl(){
String apiUrl= SystemConfigConstants.API_URL; return SystemConfigConstants.API_URL;
return apiUrl;
} }
/** /**
* site_url * site_url
*/ */
public static String getSiteUrl(){ public static String getSiteUrl(){
String siteUrl= SystemConfigConstants.SITE_URL; return SystemConfigConstants.SITE_URL;
return siteUrl;
} }
/** /**
* 腾讯mapkey tengxun_map_key * 腾讯mapkey tengxun_map_key
*/ */
public static String getTengXunMapKey(){ public static String getTengXunMapKey(){
String tengxunMapKey= SystemConfigConstants.TENGXUN_MAP_KEY; return SystemConfigConstants.TENGXUN_MAP_KEY;
return tengxunMapKey;
} }
//*********************************begin yx_system_config 业务字段 ***************************************************** //*********************************begin yx_system_config 业务字段 *****************************************************
@ -89,13 +85,6 @@ public class ShopKeyUtils {
String wechatEncodingAESKey= SystemConfigConstants.WECHAT_ENCODINGAESKEY; String wechatEncodingAESKey= SystemConfigConstants.WECHAT_ENCODINGAESKEY;
return wechatEncodingAESKey+getExtendValue(); return wechatEncodingAESKey+getExtendValue();
} }
/**
* 微信支付service
*/
public static String getYshopWeiXinPayService(){
String yshopWeiXinPayService= TenantContextHolder.getTenantId().toString() + ":"+ShopConstants.ZSW_WEIXIN_PAY_SERVICE;
return yshopWeiXinPayService+getExtendValue();
}
/** /**
* 商户号 * 商户号
*/ */
@ -117,20 +106,6 @@ public class ShopKeyUtils {
String wxPayKeyPath= SystemConfigConstants.WXPAY_KEYPATH; String wxPayKeyPath= SystemConfigConstants.WXPAY_KEYPATH;
return wxPayKeyPath+getExtendValue(); return wxPayKeyPath+getExtendValue();
} }
/**
* 微信支付小程序service
*/
public static String getYshopWeiXinMiniPayService(){
String yshopWeiXinMiniPayService= TenantContextHolder.getTenantId().toString() + ":" + ShopConstants.ZSW_WEIXIN_MINI_PAY_SERVICE;
return yshopWeiXinMiniPayService+getExtendValue();
}
/**
* 微信支付app service
*/
public static String getYshopWeiXinAppPayService(){
String yshopWeiXinAppPayService= TenantContextHolder.getTenantId().toString() + ":" + ShopConstants.ZSW_WEIXIN_APP_PAY_SERVICE;
return yshopWeiXinAppPayService+getExtendValue();
}
/** /**
* 微信小程序id * 微信小程序id
*/ */
@ -178,4 +153,26 @@ public class ShopKeyUtils {
return yshopWeiXinMaSevice+getExtendValue(); return yshopWeiXinMaSevice+getExtendValue();
} }
/**
* 微信支付小程序service
*/
public static String getYshopWeiXinMiniPayService(){
String yshopWeiXinMiniPayService= TenantContextHolder.getTenantId().toString() + ":" + ShopConstants.ZSW_WEIXIN_MINI_PAY_SERVICE;
return yshopWeiXinMiniPayService+getExtendValue();
}
/**
* 微信支付app service
*/
public static String getYshopWeiXinAppPayService(){
String yshopWeiXinAppPayService= TenantContextHolder.getTenantId().toString() + ":" + ShopConstants.ZSW_WEIXIN_APP_PAY_SERVICE;
return yshopWeiXinAppPayService+getExtendValue();
}
/**
* 微信支付service
*/
public static String getYshopWeiXinPayService(){
String yshopWeiXinPayService= TenantContextHolder.getTenantId().toString() + ":"+ShopConstants.ZSW_WEIXIN_PAY_SERVICE;
return yshopWeiXinPayService+getExtendValue();
}
} }

Loading…
Cancel
Save