Browse Source

基本完成

zyh
Loki 3 years ago
parent
commit
a89a69b145
  1. 135
      yudao-framework/yudao-spring-boot-starter-redis/src/main/java/cn/iocoder/yudao/framework/redis/config/YudaoRedisAutoConfiguration.java
  2. 3
      yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/config/YudaoWebSecurityConfigurerAdapter.java
  3. 274
      yudao-module-member/yudao-module-member-impl/src/test/java/cn/iocoder/yudao/module/member/service/user/MemberUserServiceImplTest.java
  4. 1
      zsw-bxg/src/main/java/co/yixiang/app/common/interceptor/PermissionInterceptor.java
  5. 73
      zsw-bxg/src/main/java/co/yixiang/config/CachingConfigurer.java
  6. 321
      zsw-bxg/src/main/java/co/yixiang/config/RedisConfig.java
  7. 50
      zsw-bxg/src/main/java/co/yixiang/config/StringKeyRedisSerializer.java
  8. 12
      zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreBargainQueryVo.java
  9. 6
      zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreCombinationQueryVo.java
  10. 6
      zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreSeckillQueryVo.java
  11. 6
      zsw-bxg/src/main/java/co/yixiang/modules/cart/vo/YxStoreCartQueryVo.java
  12. 12
      zsw-bxg/src/main/java/co/yixiang/modules/order/service/dto/PriceGroupDto.java
  13. 12
      zsw-bxg/src/main/java/co/yixiang/modules/order/vo/ComputeVo.java
  14. 2
      zsw-bxg/src/main/java/co/yixiang/modules/order/vo/OrderDataVo.java
  15. 8
      zsw-bxg/src/main/java/co/yixiang/modules/product/domain/YxStoreProductAttrValue.java
  16. 10
      zsw-bxg/src/main/java/co/yixiang/modules/product/vo/YxStoreProductQueryVo.java
  17. 4
      zsw-bxg/src/main/java/co/yixiang/modules/product/vo/YxStoreProductRelationQueryVo.java
  18. 132
      zsw-bxg/src/main/java/co/yixiang/utils/RedisUtils.java

135
yudao-framework/yudao-spring-boot-starter-redis/src/main/java/cn/iocoder/yudao/framework/redis/config/YudaoRedisAutoConfiguration.java

@ -1,136 +1,33 @@
package cn.iocoder.yudao.framework.redis.config; package cn.iocoder.yudao.framework.redis.config;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.DigestUtils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/** /**
* Redis 配置类 * Redis 配置类
*/ */
@Slf4j @Configuration
public class YudaoRedisAutoConfiguration extends CachingConfigurerSupport { public class YudaoRedisAutoConfiguration {
/** /**
* 创建 RedisTemplate Bean使用 JSON 序列化方式 * 创建 RedisTemplate Bean使用 JSON 序列化方式
*/ */
@Bean // @Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { // public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
// 创建 RedisTemplate 对象 // // 创建 RedisTemplate 对象
RedisTemplate<String, Object> template = new RedisTemplate<>(); // RedisTemplate<String, Object> template = new RedisTemplate<>();
//序列化 // // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); // template.setConnectionFactory(factory);
// value值的序列化采用fastJsonRedisSerializer // // 使用 String 序列化方式,序列化 KEY 。
template.setValueSerializer(jackson2JsonRedisSerializer); // template.setKeySerializer(RedisSerializer.string());
template.setHashValueSerializer(jackson2JsonRedisSerializer); // template.setHashKeySerializer(RedisSerializer.string());
// key的序列化采用StringRedisSerializer // // 使用 JSON 序列化方式(库是 Jackson ),序列化 VALUE 。
template.setKeySerializer(new StringRedisSerializer()); // template.setValueSerializer(RedisSerializer.json());
template.setHashKeySerializer(new StringRedisSerializer()); // template.setHashValueSerializer(RedisSerializer.json());
// 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。 // return template;
template.setConnectionFactory(factory); // }
return template;
}
/**
* 自定义缓存key生成策略默认将使用该策略
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
Map<String,Object> container = new HashMap<>(3);
Class<?> targetClassClass = target.getClass();
// 类地址
container.put("class",targetClassClass.toGenericString());
// 方法名称
container.put("methodName",method.getName());
// 包名称
container.put("package",targetClassClass.getPackage());
// 参数列表
for (int i = 0; i < params.length; i++) {
container.put(String.valueOf(i),params[i]);
}
// 转为JSON字符串
String jsonString = JSONUtil.toJsonStr(container);
// 做SHA256 Hash计算,得到一个SHA256摘要作为Key
return SecureUtil.sha256(jsonString);
// return DigestUtils.sha256Hex(jsonString);
};
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// 异常处理,当Redis发生异常时,打印日志,但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error("Redis occur handleCacheClearError:", e);
}
};
}
class StringRedisSerializer implements RedisSerializer<Object> {
private final Charset charset;
StringRedisSerializer() {
this(StandardCharsets.UTF_8);
}
private StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
}
@Override
public String deserialize(byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset));
}
@Override
public byte[] serialize(Object object) {
String string = JSONUtil.toJsonStr(object);
if (StrUtil.isBlank(string)) {
return null;
}
string = string.replace("\"", "");
return string.getBytes(charset);
}
}
} }

3
yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/config/YudaoWebSecurityConfigurerAdapter.java

@ -143,7 +143,8 @@ public class YudaoWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdap
; ;
// // 添加 JWT Filter // // 添加 JWT Filter
// httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
} }
private String buildAdminApi(String url) { private String buildAdminApi(String url) {

274
yudao-module-member/yudao-module-member-impl/src/test/java/cn/iocoder/yudao/module/member/service/user/MemberUserServiceImplTest.java

@ -1,137 +1,137 @@
package cn.iocoder.yudao.module.member.service.user; //package cn.iocoder.yudao.module.member.service.user;
//
import cn.hutool.core.util.RandomUtil; //import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; //import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; //import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration; //import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest; //import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest;
import cn.iocoder.yudao.module.infra.api.file.FileApi; //import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppUserUpdateMobileReqVO; //import cn.iocoder.yudao.module.member.controller.app.user.vo.AppUserUpdateMobileReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO; //import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper; //import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.service.auth.MemberAuthServiceImpl; //import cn.iocoder.yudao.module.member.service.auth.MemberAuthServiceImpl;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi; //import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import org.junit.jupiter.api.Test; //import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean; //import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import; //import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate; //import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder; //import org.springframework.security.crypto.password.PasswordEncoder;
//
import javax.annotation.Resource; //import javax.annotation.Resource;
import java.io.ByteArrayInputStream; //import java.io.ByteArrayInputStream;
import java.util.function.Consumer; //import java.util.function.Consumer;
//
import static cn.hutool.core.util.RandomUtil.*; //import static cn.hutool.core.util.RandomUtil.*;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; //import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString; //import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomString;
import static org.junit.jupiter.api.Assertions.assertEquals; //import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.eq; //import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.when; //import static org.mockito.Mockito.when;
//
// TODO @芋艿:单测的 review,等逻辑都达成一致后 //// TODO @芋艿:单测的 review,等逻辑都达成一致后
/** ///**
* {@link MemberUserServiceImpl} 的单元测试类 // * {@link MemberUserServiceImpl} 的单元测试类
* // *
* @author 宋天 // * @author 宋天
*/ // */
@Import({MemberUserServiceImpl.class, YudaoRedisAutoConfiguration.class}) //@Import({MemberUserServiceImpl.class, YudaoRedisAutoConfiguration.class})
public class MemberUserServiceImplTest extends BaseDbAndRedisUnitTest { //public class MemberUserServiceImplTest extends BaseDbAndRedisUnitTest {
//
@Resource // @Resource
private MemberUserServiceImpl memberUserService; // private MemberUserServiceImpl memberUserService;
//
@Resource // @Resource
private StringRedisTemplate stringRedisTemplate; // private StringRedisTemplate stringRedisTemplate;
//
@Resource // @Resource
private MemberUserMapper userMapper; // private MemberUserMapper userMapper;
//
@MockBean // @MockBean
private MemberAuthServiceImpl authService; // private MemberAuthServiceImpl authService;
//
@MockBean // @MockBean
private PasswordEncoder passwordEncoder; // private PasswordEncoder passwordEncoder;
//
@MockBean // @MockBean
private SmsCodeApi smsCodeApi; // private SmsCodeApi smsCodeApi;
@MockBean // @MockBean
private FileApi fileApi; // private FileApi fileApi;
//
@Test // @Test
public void testUpdateNickName_success(){ // public void testUpdateNickName_success(){
// mock 数据 // // mock 数据
MemberUserDO userDO = randomUserDO(); // MemberUserDO userDO = randomUserDO();
userMapper.insert(userDO); // userMapper.insert(userDO);
//
// 随机昵称 // // 随机昵称
String newNickName = randomString(); // String newNickName = randomString();
//
// 调用接口修改昵称 // // 调用接口修改昵称
memberUserService.updateUserNickname(userDO.getId(),newNickName); // memberUserService.updateUserNickname(userDO.getId(),newNickName);
// 查询新修改后的昵称 // // 查询新修改后的昵称
String nickname = memberUserService.getUser(userDO.getId()).getNickname(); // String nickname = memberUserService.getUser(userDO.getId()).getNickname();
// 断言 // // 断言
assertEquals(newNickName,nickname); // assertEquals(newNickName,nickname);
} // }
//
@Test // @Test
public void testUpdateAvatar_success() throws Exception { // public void testUpdateAvatar_success() throws Exception {
// mock 数据 // // mock 数据
MemberUserDO dbUser = randomUserDO(); // MemberUserDO dbUser = randomUserDO();
userMapper.insert(dbUser); // userMapper.insert(dbUser);
//
// 准备参数 // // 准备参数
Long userId = dbUser.getId(); // Long userId = dbUser.getId();
byte[] avatarFileBytes = randomBytes(10); // byte[] avatarFileBytes = randomBytes(10);
ByteArrayInputStream avatarFile = new ByteArrayInputStream(avatarFileBytes); // ByteArrayInputStream avatarFile = new ByteArrayInputStream(avatarFileBytes);
// mock 方法 // // mock 方法
String avatar = randomString(); // String avatar = randomString();
when(fileApi.createFile(eq(avatarFileBytes))).thenReturn(avatar); // when(fileApi.createFile(eq(avatarFileBytes))).thenReturn(avatar);
// 调用 // // 调用
String str = memberUserService.updateUserAvatar(userId, avatarFile); // String str = memberUserService.updateUserAvatar(userId, avatarFile);
// 断言 // // 断言
assertEquals(avatar, str); // assertEquals(avatar, str);
} // }
//
@Test // @Test
public void updateMobile_success(){ // public void updateMobile_success(){
// mock数据 // // mock数据
String oldMobile = randomNumbers(11); // String oldMobile = randomNumbers(11);
MemberUserDO userDO = randomUserDO(); // MemberUserDO userDO = randomUserDO();
userDO.setMobile(oldMobile); // userDO.setMobile(oldMobile);
userMapper.insert(userDO); // userMapper.insert(userDO);
//
// TODO 芋艿:需要修复该单元测试,重构多模块带来的 // // TODO 芋艿:需要修复该单元测试,重构多模块带来的
// 旧手机和旧验证码 // // 旧手机和旧验证码
// SmsCodeDO codeDO = new SmsCodeDO(); //// SmsCodeDO codeDO = new SmsCodeDO();
String oldCode = RandomUtil.randomString(4); // String oldCode = RandomUtil.randomString(4);
// codeDO.setMobile(userDO.getMobile()); //// codeDO.setMobile(userDO.getMobile());
// codeDO.setCode(oldCode); //// codeDO.setCode(oldCode);
// codeDO.setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene()); //// codeDO.setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene());
// codeDO.setUsed(Boolean.FALSE); //// codeDO.setUsed(Boolean.FALSE);
// when(smsCodeService.checkCodeIsExpired(codeDO.getMobile(),codeDO.getCode(),codeDO.getScene())).thenReturn(codeDO); //// when(smsCodeService.checkCodeIsExpired(codeDO.getMobile(),codeDO.getCode(),codeDO.getScene())).thenReturn(codeDO);
//
// 更新手机号 // // 更新手机号
String newMobile = randomNumbers(11); // String newMobile = randomNumbers(11);
String newCode = randomNumbers(4); // String newCode = randomNumbers(4);
AppUserUpdateMobileReqVO reqVO = new AppUserUpdateMobileReqVO(); // AppUserUpdateMobileReqVO reqVO = new AppUserUpdateMobileReqVO();
reqVO.setMobile(newMobile); // reqVO.setMobile(newMobile);
reqVO.setCode(newCode); // reqVO.setCode(newCode);
reqVO.setOldMobile(oldMobile); // reqVO.setOldMobile(oldMobile);
reqVO.setOldCode(oldCode); // reqVO.setOldCode(oldCode);
memberUserService.updateUserMobile(userDO.getId(),reqVO); // memberUserService.updateUserMobile(userDO.getId(),reqVO);
//
assertEquals(memberUserService.getUser(userDO.getId()).getMobile(),newMobile); // assertEquals(memberUserService.getUser(userDO.getId()).getMobile(),newMobile);
} // }
//
// ========== 随机对象 ========== // // ========== 随机对象 ==========
//
@SafeVarargs // @SafeVarargs
private static MemberUserDO randomUserDO(Consumer<MemberUserDO>... consumers) { // private static MemberUserDO randomUserDO(Consumer<MemberUserDO>... consumers) {
Consumer<MemberUserDO> consumer = (o) -> { // Consumer<MemberUserDO> consumer = (o) -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 // o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
}; // };
return randomPojo(MemberUserDO.class, ArrayUtils.append(consumer, consumers)); // return randomPojo(MemberUserDO.class, ArrayUtils.append(consumer, consumers));
} // }
//
} //}

1
zsw-bxg/src/main/java/co/yixiang/app/common/interceptor/PermissionInterceptor.java

@ -85,7 +85,6 @@ public class PermissionInterceptor implements HandlerInterceptor {
} }
private void setToThreadLocal(Map<String,Claim> map) { private void setToThreadLocal(Map<String,Claim> map) {
log.info("map:{}",map);
Integer uid = map.get("uid").asInt(); Integer uid = map.get("uid").asInt();
Integer scope = map.get("scope").asInt(); Integer scope = map.get("scope").asInt();
YxUser user = userService.getById(uid); YxUser user = userService.getById(uid);

73
zsw-bxg/src/main/java/co/yixiang/config/CachingConfigurer.java

@ -0,0 +1,73 @@
package co.yixiang.config;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
public class CachingConfigurer extends CachingConfigurerSupport {
/**
* 自定义缓存key生成策略默认将使用该策略
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
Map<String,Object> container = new HashMap<>(3);
Class<?> targetClassClass = target.getClass();
// 类地址
container.put("class",targetClassClass.toGenericString());
// 方法名称
container.put("methodName",method.getName());
// 包名称
container.put("package",targetClassClass.getPackage());
// 参数列表
for (int i = 0; i < params.length; i++) {
container.put(String.valueOf(i),params[i]);
}
// 转为JSON字符串
String jsonString = JSON.toJSONString(container);
// 做SHA256 Hash计算,得到一个SHA256摘要作为Key
return DigestUtils.sha256Hex(jsonString);
};
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// 异常处理,当Redis发生异常时,打印日志,但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error("Redis occur handleCacheClearError:", e);
}
};
}
}

321
zsw-bxg/src/main/java/co/yixiang/config/RedisConfig.java

@ -1,205 +1,118 @@
///** /**
// * Copyright (C) 2018-2022 * Copyright (C) 2018-2022
// * All rights reserved, Designed By www.yixiang.co * All rights reserved, Designed By www.yixiang.co
//
// */ */
//package co.yixiang.config; package co.yixiang.config;
//
//import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
//import co.yixiang.utils.StringUtils; import co.yixiang.utils.StringUtils;
//import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.ParserConfig;
//import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SerializerFeature;
//import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
//import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
//import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.cache.Cache; import org.springframework.cache.Cache;
//import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.CachingConfigurerSupport;
//import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.CacheErrorHandler;
//import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
//import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.context.annotation.Primary;
//import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.cache.RedisCacheConfiguration;
//import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisOperations;
//import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext;
// import org.springframework.data.redis.serializer.RedisSerializer;
//import java.nio.charset.Charset;
//import java.nio.charset.StandardCharsets; import java.nio.charset.Charset;
//import java.time.Duration; import java.nio.charset.StandardCharsets;
//import java.util.HashMap; import java.time.Duration;
//import java.util.Map; import java.util.HashMap;
// import java.util.Map;
///**
// * @author Zheng Jie /**
// * @date 2018-11-24 * @author Zheng Jie
// */ * @date 2018-11-24
//@Slf4j */
//@Configuration(proxyBeanMethods = false) @Slf4j
//@EnableCaching @Configuration
//@ConditionalOnClass(RedisOperations.class)
//@EnableConfigurationProperties(RedisProperties.class) //@EnableConfigurationProperties(RedisProperties.class)
//public class RedisConfig extends CachingConfigurerSupport { public class RedisConfig {
//
// /** /**
// * 设置 redis 数据默认过期时间,默认2小时 * 设置 redis 数据默认过期时间默认2小时
// * 设置@cacheable 序列化方式 * 设置@cacheable 序列化方式
// */ */
// @Bean @Bean
// public RedisCacheConfiguration redisCacheConfiguration(){ public RedisCacheConfiguration redisCacheConfiguration(){
// FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
// configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2)); configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2));
// return configuration; return configuration;
// } }
//
// @SuppressWarnings("all") @Bean(name = "redisTemplate")
// @Bean(name = "redisTemplate") // @ConditionalOnMissingBean(name = "redisTemplate")
// @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>();
// RedisTemplate<Object, Object> template = new RedisTemplate<>(); //序列化
// //序列化 FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); // value值的序列化采用fastJsonRedisSerializer
// // value值的序列化采用fastJsonRedisSerializer template.setValueSerializer(fastJsonRedisSerializer);
// template.setValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer);
// template.setHashValueSerializer(fastJsonRedisSerializer); // 全局开启AutoType,这里方便开发,使用全局的方式
// // 全局开启AutoType,这里方便开发,使用全局的方式 ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 建议使用这种方式,小范围指定白名单
// // 建议使用这种方式,小范围指定白名单 // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain"); // key的序列化采用StringRedisSerializer
// // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringKeyRedisSerializer());
// template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringKeyRedisSerializer());
// template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory);
// template.setConnectionFactory(redisConnectionFactory); return template;
// return template; }
// }
//
// /**
// * 自定义缓存key生成策略,默认将使用该策略 }
// */
// @Bean /**
// @Override * Value 序列化
// public KeyGenerator keyGenerator() { *
// return (target, method, params) -> { * @author /
// Map<String,Object> container = new HashMap<>(3); * @param <T>
// Class<?> targetClassClass = target.getClass(); */
// // 类地址 class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
// container.put("class",targetClassClass.toGenericString());
// // 方法名称 private final Class<T> clazz;
// container.put("methodName",method.getName());
// // 包名称 FastJsonRedisSerializer(Class<T> clazz) {
// container.put("package",targetClassClass.getPackage()); super();
// // 参数列表 this.clazz = clazz;
// for (int i = 0; i < params.length; i++) { }
// container.put(String.valueOf(i),params[i]);
// } @Override
// // 转为JSON字符串 public byte[] serialize(T t) {
// String jsonString = JSON.toJSONString(container); if (t == null) {
// // 做SHA256 Hash计算,得到一个SHA256摘要作为Key return new byte[0];
// return DigestUtils.sha256Hex(jsonString); }
// }; return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
// } }
//
// @Bean @Override
// @Override public T deserialize(byte[] bytes) {
// public CacheErrorHandler errorHandler() { if (bytes == null || bytes.length <= 0) {
// // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 return null;
// log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); }
// return new CacheErrorHandler() { String str = new String(bytes, StandardCharsets.UTF_8);
// @Override return JSON.parseObject(str, clazz);
// public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { }
// log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
// } }
//
// @Override
// public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
// log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
// }
//
// @Override
// public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
// log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
// }
//
// @Override
// public void handleCacheClearError(RuntimeException e, Cache cache) {
// log.error("Redis occur handleCacheClearError:", e);
// }
// };
// }
//
//}
//
///**
// * Value 序列化
// *
// * @author /
// * @param <T>
// */
// class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
//
// private final Class<T> clazz;
//
// FastJsonRedisSerializer(Class<T> clazz) {
// super();
// this.clazz = clazz;
// }
//
// @Override
// public byte[] serialize(T t) {
// if (t == null) {
// return new byte[0];
// }
// return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
// }
//
// @Override
// public T deserialize(byte[] bytes) {
// if (bytes == null || bytes.length <= 0) {
// return null;
// }
// String str = new String(bytes, StandardCharsets.UTF_8);
// return JSON.parseObject(str, clazz);
// }
//
//}
//
///**
// * 重写序列化器
// *
// * @author /
// */
//class StringRedisSerializer implements RedisSerializer<Object> {
//
// private final Charset charset;
//
// StringRedisSerializer() {
// this(StandardCharsets.UTF_8);
// }
//
// private StringRedisSerializer(Charset charset) {
// Assert.notNull(charset, "Charset must not be null!");
// this.charset = charset;
// }
//
// @Override
// public String deserialize(byte[] bytes) {
// return (bytes == null ? null : new String(bytes, charset));
// }
//
// @Override
// public byte[] serialize(Object object) {
// String string = JSON.toJSONString(object);
// if (StringUtils.isBlank(string)) {
// return null;
// }
// string = string.replace("\"", "");
// return string.getBytes(charset);
// }
//}

50
zsw-bxg/src/main/java/co/yixiang/config/StringKeyRedisSerializer.java

@ -0,0 +1,50 @@
package co.yixiang.config;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@Slf4j
public class StringKeyRedisSerializer implements RedisSerializer<Object> {
private final Charset charset;
public StringKeyRedisSerializer() {
this(StandardCharsets.UTF_8);
}
private StringKeyRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
}
@Override
public byte[] serialize(Object object) throws SerializationException {
String string = JSONUtil.toJsonStr(object);
if (StrUtil.isBlank(string)) {
return null;
}
log.info("redis serialize:{}",string);
string = string.replace("\"", "");
if (ObjectUtil.isNotEmpty(TenantContextHolder.getTenantId())){
string = StrUtil.format("{}_{}",TenantContextHolder.getTenantId().toString(),string);
}
return string.getBytes(charset);
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
String rs = (bytes == null ? null : new String(bytes));
log.info("redis deserialize:{}",rs);
return rs;
}
}

12
zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreBargainQueryVo.java

@ -56,22 +56,22 @@ public class YxStoreBargainQueryVo implements Serializable {
@ApiModelProperty(value = "砍价产品名称") @ApiModelProperty(value = "砍价产品名称")
private String storeName; private String storeName;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "砍价金额") @ApiModelProperty(value = "砍价金额")
private BigDecimal price; private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "砍价商品最低价") @ApiModelProperty(value = "砍价商品最低价")
private BigDecimal minPrice; private BigDecimal minPrice;
@ApiModelProperty(value = "每次购买的砍价产品数量") @ApiModelProperty(value = "每次购买的砍价产品数量")
private Integer num; private Integer num;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "用户每次砍价的最大金额") @ApiModelProperty(value = "用户每次砍价的最大金额")
private BigDecimal bargainMaxPrice; private BigDecimal bargainMaxPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "用户每次砍价的最小金额") @ApiModelProperty(value = "用户每次砍价的最小金额")
private BigDecimal bargainMinPrice; private BigDecimal bargainMinPrice;
@ -90,14 +90,14 @@ public class YxStoreBargainQueryVo implements Serializable {
@ApiModelProperty(value = "砍价活动简介") @ApiModelProperty(value = "砍价活动简介")
private String info; private String info;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "成本价") @ApiModelProperty(value = "成本价")
private BigDecimal cost; private BigDecimal cost;
@ApiModelProperty(value = "排序") @ApiModelProperty(value = "排序")
private Integer sort; private Integer sort;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "邮费") @ApiModelProperty(value = "邮费")
private BigDecimal postage; private BigDecimal postage;

6
zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreCombinationQueryVo.java

@ -62,11 +62,11 @@ public class YxStoreCombinationQueryVo implements Serializable {
@ApiModelProperty(value = "简介") @ApiModelProperty(value = "简介")
private String info; private String info;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "价格") @ApiModelProperty(value = "价格")
private BigDecimal price; private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "商品价格") @ApiModelProperty(value = "商品价格")
private BigDecimal productPrice; private BigDecimal productPrice;
@ -82,7 +82,7 @@ public class YxStoreCombinationQueryVo implements Serializable {
@ApiModelProperty(value = "是否包邮1是0否") @ApiModelProperty(value = "是否包邮1是0否")
private Integer isPostage; private Integer isPostage;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "邮费") @ApiModelProperty(value = "邮费")
private BigDecimal postage; private BigDecimal postage;

6
zsw-bxg/src/main/java/co/yixiang/modules/activity/vo/YxStoreSeckillQueryVo.java

@ -51,15 +51,15 @@ public class YxStoreSeckillQueryVo implements Serializable{
} }
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "价格") @ApiModelProperty(value = "价格")
private BigDecimal price; private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "成本") @ApiModelProperty(value = "成本")
private BigDecimal cost; private BigDecimal cost;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "原价") @ApiModelProperty(value = "原价")
private BigDecimal otPrice; private BigDecimal otPrice;

6
zsw-bxg/src/main/java/co/yixiang/modules/cart/vo/YxStoreCartQueryVo.java

@ -54,17 +54,17 @@ public class YxStoreCartQueryVo implements Serializable {
private YxStoreProductQueryVo productInfo; private YxStoreProductQueryVo productInfo;
@ApiModelProperty(value = "成本价") @ApiModelProperty(value = "成本价")
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
private Double costPrice; private Double costPrice;
@ApiModelProperty(value = "真实价格") @ApiModelProperty(value = "真实价格")
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
private Double truePrice; private Double truePrice;
@ApiModelProperty(value = "真实库存") @ApiModelProperty(value = "真实库存")
private Integer trueStock; private Integer trueStock;
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
@ApiModelProperty(value = "vip真实价格") @ApiModelProperty(value = "vip真实价格")
private Double vipTruePrice; private Double vipTruePrice;

12
zsw-bxg/src/main/java/co/yixiang/modules/order/service/dto/PriceGroupDto.java

@ -14,21 +14,21 @@ import java.math.BigDecimal;
@Data @Data
public class PriceGroupDto { public class PriceGroupDto {
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal costPrice; private BigDecimal costPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal storeFreePostage; private BigDecimal storeFreePostage;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal storePostage; private BigDecimal storePostage;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal totalPrice; private BigDecimal totalPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal vipPrice; private BigDecimal vipPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payIntegral; private BigDecimal payIntegral;
} }

12
zsw-bxg/src/main/java/co/yixiang/modules/order/vo/ComputeVo.java

@ -21,23 +21,23 @@ import java.math.BigDecimal;
@AllArgsConstructor @AllArgsConstructor
public class ComputeVo implements Serializable { public class ComputeVo implements Serializable {
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal couponPrice; private BigDecimal couponPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal deductionPrice; private BigDecimal deductionPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payPostage; private BigDecimal payPostage;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payPrice; private BigDecimal payPrice;
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal totalPrice; private BigDecimal totalPrice;
private Double usedIntegral; //使用了多少积分 private Double usedIntegral; //使用了多少积分
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payIntegral; private BigDecimal payIntegral;
} }

2
zsw-bxg/src/main/java/co/yixiang/modules/order/vo/OrderDataVo.java

@ -14,7 +14,7 @@ import java.io.Serializable;
@Data @Data
public class OrderDataVo implements Serializable { public class OrderDataVo implements Serializable {
private Integer count; private Integer count;
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
private Double price; private Double price;
private String time; private String time;
} }

8
zsw-bxg/src/main/java/co/yixiang/modules/product/domain/YxStoreProductAttrValue.java

@ -68,17 +68,17 @@ public class YxStoreProductAttrValue implements Serializable {
/** 属性金额 */ /** 属性金额 */
@ApiModelProperty(value = "属性金额") @ApiModelProperty(value = "属性金额")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price; private BigDecimal price;
/** 拼团属性对应的金额 */ /** 拼团属性对应的金额 */
@ApiModelProperty(value = "拼团属性对应的金额") @ApiModelProperty(value = "拼团属性对应的金额")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal pinkPrice; private BigDecimal pinkPrice;
/** 秒杀属性对应的金额 */ /** 秒杀属性对应的金额 */
@ApiModelProperty(value = "秒杀属性对应的金额") @ApiModelProperty(value = "秒杀属性对应的金额")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal seckillPrice; private BigDecimal seckillPrice;
/** 图片 */ /** 图片 */
@ -94,7 +94,7 @@ public class YxStoreProductAttrValue implements Serializable {
/** 成本价 */ /** 成本价 */
@ApiModelProperty(value = "成本价") @ApiModelProperty(value = "成本价")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal cost; private BigDecimal cost;
/** 商品条码 */ /** 商品条码 */

10
zsw-bxg/src/main/java/co/yixiang/modules/product/vo/YxStoreProductQueryVo.java

@ -80,19 +80,19 @@ public class YxStoreProductQueryVo implements Serializable {
private String cateId; private String cateId;
@ApiModelProperty(value = "商品价格") @ApiModelProperty(value = "商品价格")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price; private BigDecimal price;
@ApiModelProperty(value = "会员价格") @ApiModelProperty(value = "会员价格")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal vipPrice; private BigDecimal vipPrice;
@ApiModelProperty(value = "市场价") @ApiModelProperty(value = "市场价")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal otPrice; private BigDecimal otPrice;
@ApiModelProperty(value = "邮费") @ApiModelProperty(value = "邮费")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal postage; private BigDecimal postage;
@ApiModelProperty(value = "单位名") @ApiModelProperty(value = "单位名")
@ -114,7 +114,7 @@ public class YxStoreProductQueryVo implements Serializable {
private Integer isPostage; private Integer isPostage;
@ApiModelProperty(value = "成本价") @ApiModelProperty(value = "成本价")
//@JsonSerialize(using = BigDecimalSerializer.class) @JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal cost; private BigDecimal cost;
@ApiModelProperty(value = "秒杀状态 0 未开启 1已开启") @ApiModelProperty(value = "秒杀状态 0 未开启 1已开启")

4
zsw-bxg/src/main/java/co/yixiang/modules/product/vo/YxStoreProductRelationQueryVo.java

@ -46,14 +46,14 @@ public class YxStoreProductRelationQueryVo implements Serializable {
private Integer isShow; private Integer isShow;
@ApiModelProperty(value = "原价") @ApiModelProperty(value = "原价")
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
private Double otPrice; private Double otPrice;
@ApiModelProperty(value = "父ID") @ApiModelProperty(value = "父ID")
private Integer pid; private Integer pid;
@ApiModelProperty(value = "产品价格") @ApiModelProperty(value = "产品价格")
//@JsonSerialize(using = DoubleSerializer.class) @JsonSerialize(using = DoubleSerializer.class)
private Double price; private Double price;
@ApiModelProperty(value = "产品销量") @ApiModelProperty(value = "产品销量")

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

@ -8,9 +8,6 @@
*/ */
package co.yixiang.utils; package co.yixiang.utils;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import com.mchange.v2.net.LocalHostManager;
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;
@ -18,18 +15,23 @@ import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/** /**
* @author / * @author /
*/ */
@Component @Component
@SuppressWarnings({"unchecked","all"})
public class RedisUtils { public class RedisUtils {
@Autowired
private RedisTemplate stringRedisTemplate; @Resource
private RedisTemplate<String, Object> redisTemplate;
// =============================commonold============================
/** /**
* 指定缓存失效时间 * 指定缓存失效时间
@ -37,10 +39,9 @@ public class RedisUtils {
* @param time 时间() * @param time 时间()
*/ */
public boolean expire(String key, long time) { public boolean expire(String key, long time) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
if (time > 0) { if (time > 0) {
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); redisTemplate.expire(key, time, TimeUnit.SECONDS);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -55,8 +56,7 @@ public class RedisUtils {
* @return 时间() 返回0代表为永久有效 * @return 时间() 返回0代表为永久有效
*/ */
public long getExpire(String key) { public long getExpire(String key) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.getExpire(key, TimeUnit.SECONDS);
return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
} }
/** /**
@ -65,9 +65,8 @@ public class RedisUtils {
* @return / * @return /
*/ */
public List<String> scan(String pattern) { public List<String> scan(String pattern) {
pattern = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),pattern);
ScanOptions options = ScanOptions.scanOptions().match(pattern).build(); ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection(); RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options); Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
@ -90,9 +89,8 @@ 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 = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),patternKey);
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build(); ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisConnectionFactory factory = stringRedisTemplate.getConnectionFactory(); RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection(); RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options); Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>(size); List<String> result = new ArrayList<>(size);
@ -127,8 +125,7 @@ public class RedisUtils {
*/ */
public boolean hasKey(String key) { public boolean hasKey(String key) {
try { try {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.hasKey(key);
return stringRedisTemplate.hasKey(key);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
@ -142,14 +139,9 @@ public class RedisUtils {
public void del(String... key) { public void del(String... key) {
if (key != null && key.length > 0) { if (key != null && key.length > 0) {
if (key.length == 1) { if (key.length == 1) {
stringRedisTemplate.delete(StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key[0])); redisTemplate.delete(key[0]);
} else { } else {
stringRedisTemplate.delete( redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
CollectionUtils
.arrayToList(key)
.stream()
.map(s-> StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),s))
.collect(Collectors.toList()));
} }
} }
} }
@ -162,13 +154,11 @@ public class RedisUtils {
* @return * @return
*/ */
public Object get(String key) { public Object get(String key) {
return key == null ? null : stringRedisTemplate.opsForValue().get(StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key)); return key == null ? null : redisTemplate.opsForValue().get(key);
} }
public String getY(String key){ public String getY(String key){
return key == null || !stringRedisTemplate.hasKey(StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key)) return key == null || !redisTemplate.hasKey(key) ? "" : redisTemplate.opsForValue().get(key).toString();
? ""
: stringRedisTemplate.opsForValue().get(StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key)).toString();
} }
/** /**
@ -177,8 +167,8 @@ public class RedisUtils {
* @return * @return
*/ */
public List<Object> multiGet(List<String> keys) { public List<Object> multiGet(List<String> keys) {
keys = keys.stream().map(s-> StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),s)).collect(Collectors.toList()); Object obj = redisTemplate.opsForValue().multiGet(keys);
return stringRedisTemplate.opsForValue().multiGet(keys); return null;
} }
/** /**
@ -188,9 +178,8 @@ public class RedisUtils {
* @return true成功 false失败 * @return true成功 false失败
*/ */
public boolean set(String key, Object value) { public boolean set(String key, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForValue().set(key, value); redisTemplate.opsForValue().set(key, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -206,10 +195,9 @@ 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 = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
if (time > 0) { if (time > 0) {
stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else { } else {
set(key, value); set(key, value);
} }
@ -229,10 +217,9 @@ 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 = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
if (time > 0) { if (time > 0) {
stringRedisTemplate.opsForValue().set(key, value, time, timeUnit); redisTemplate.opsForValue().set(key, value, time, timeUnit);
} else { } else {
set(key, value); set(key, value);
} }
@ -252,8 +239,7 @@ public class RedisUtils {
* @return * @return
*/ */
public Object hget(String key, String item) { public Object hget(String key, String item) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.opsForHash().get(key, item);
return stringRedisTemplate.opsForHash().get(key, item);
} }
/** /**
@ -262,8 +248,7 @@ public class RedisUtils {
* @return 对应的多个键值 * @return 对应的多个键值
*/ */
public Map<Object, Object> hmget(String key) { public Map<Object, Object> hmget(String key) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.opsForHash().entries(key);
return stringRedisTemplate.opsForHash().entries(key);
} }
@ -274,9 +259,8 @@ public class RedisUtils {
* @return true 成功 false 失败 * @return true 成功 false 失败
*/ */
public boolean hmset(String key, Map<String, Object> map) { public boolean hmset(String key, Map<String, Object> map) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForHash().putAll(key, map); redisTemplate.opsForHash().putAll(key, map);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -292,9 +276,8 @@ public class RedisUtils {
* @return true成功 false失败 * @return true成功 false失败
*/ */
public boolean hmset(String key, Map<String, Object> map, long time) { public boolean hmset(String key, Map<String, Object> map, long time) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForHash().putAll(key, map); redisTemplate.opsForHash().putAll(key, map);
if (time > 0) { if (time > 0) {
expire(key, time); expire(key, time);
} }
@ -314,9 +297,8 @@ public class RedisUtils {
* @return true 成功 false失败 * @return true 成功 false失败
*/ */
public boolean hset(String key, String item, Object value) { public boolean hset(String key, String item, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForHash().put(key, item, value); redisTemplate.opsForHash().put(key, item, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -334,9 +316,8 @@ public class RedisUtils {
* @return true 成功 false失败 * @return true 成功 false失败
*/ */
public boolean hset(String key, String item, Object value, long time) { public boolean hset(String key, String item, Object value, long time) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForHash().put(key, item, value); redisTemplate.opsForHash().put(key, item, value);
if (time > 0) { if (time > 0) {
expire(key, time); expire(key, time);
} }
@ -354,8 +335,7 @@ public class RedisUtils {
* @param item 可以使多个 不能为null * @param item 可以使多个 不能为null
*/ */
public void hdel(String key, Object... item) { public void hdel(String key, Object... item) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); redisTemplate.opsForHash().delete(key, item);
stringRedisTemplate.opsForHash().delete(key, item);
} }
/** /**
@ -366,8 +346,7 @@ public class RedisUtils {
* @return true 存在 false不存在 * @return true 存在 false不存在
*/ */
public boolean hHasKey(String key, String item) { public boolean hHasKey(String key, String item) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.opsForHash().hasKey(key, item);
return stringRedisTemplate.opsForHash().hasKey(key, item);
} }
/** /**
@ -379,8 +358,7 @@ public class RedisUtils {
* @return * @return
*/ */
public double hincr(String key, String item, double by) { public double hincr(String key, String item, double by) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.opsForHash().increment(key, item, by);
return stringRedisTemplate.opsForHash().increment(key, item, by);
} }
/** /**
@ -392,8 +370,7 @@ public class RedisUtils {
* @return * @return
*/ */
public double hdecr(String key, String item, double by) { public double hdecr(String key, String item, double by) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key); return redisTemplate.opsForHash().increment(key, item, -by);
return stringRedisTemplate.opsForHash().increment(key, item, -by);
} }
// ============================set============================= // ============================set=============================
@ -405,9 +382,8 @@ public class RedisUtils {
* @return * @return
*/ */
public Set<Object> sGet(String key) { public Set<Object> sGet(String key) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForSet().members(key); return redisTemplate.opsForSet().members(key);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -422,9 +398,8 @@ public class RedisUtils {
* @return true 存在 false不存在 * @return true 存在 false不存在
*/ */
public boolean sHasKey(String key, Object value) { public boolean sHasKey(String key, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForSet().isMember(key, value); return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
@ -439,9 +414,8 @@ public class RedisUtils {
* @return 成功个数 * @return 成功个数
*/ */
public long sSet(String key, Object... values) { public long sSet(String key, Object... values) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForSet().add(key, values); return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return 0; return 0;
@ -456,9 +430,8 @@ public class RedisUtils {
* @return 成功个数 * @return 成功个数
*/ */
public long sSetAndTime(String key, long time, Object... values) { public long sSetAndTime(String key, long time, Object... values) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
Long count = stringRedisTemplate.opsForSet().add(key, values); Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) { if (time > 0) {
expire(key, time); expire(key, time);
} }
@ -475,9 +448,8 @@ public class RedisUtils {
* @return * @return
*/ */
public long sGetSetSize(String key) { public long sGetSetSize(String key) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForSet().size(key); return redisTemplate.opsForSet().size(key);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return 0; return 0;
@ -491,9 +463,8 @@ public class RedisUtils {
* @return 移除的个数 * @return 移除的个数
*/ */
public long setRemove(String key, Object... values) { public long setRemove(String key, Object... values) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
Long count = stringRedisTemplate.opsForSet().remove(key, values); Long count = redisTemplate.opsForSet().remove(key, values);
return count; return count;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -511,9 +482,8 @@ public class RedisUtils {
* @return * @return
*/ */
public List<Object> lGet(String key, long start, long end) { public List<Object> lGet(String key, long start, long end) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForList().range(key, start, end); return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -526,9 +496,8 @@ public class RedisUtils {
* @return * @return
*/ */
public long lGetListSize(String key) { public long lGetListSize(String key) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForList().size(key); return redisTemplate.opsForList().size(key);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return 0; return 0;
@ -542,9 +511,8 @@ public class RedisUtils {
* @return * @return
*/ */
public Object lGetIndex(String key, long index) { public Object lGetIndex(String key, long index) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForList().index(key, index); return redisTemplate.opsForList().index(key, index);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
@ -558,9 +526,8 @@ public class RedisUtils {
* @return * @return
*/ */
public boolean lSet(String key, Object value) { public boolean lSet(String key, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForList().rightPush(key, value); redisTemplate.opsForList().rightPush(key, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -576,9 +543,8 @@ public class RedisUtils {
* @return * @return
*/ */
public boolean lSet(String key, Object value, long time) { public boolean lSet(String key, Object value, long time) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForList().rightPush(key, value); redisTemplate.opsForList().rightPush(key, value);
if (time > 0) { if (time > 0) {
expire(key, time); expire(key, time);
} }
@ -596,9 +562,8 @@ public class RedisUtils {
* @return * @return
*/ */
public boolean lSet(String key, List<Object> value) { public boolean lSet(String key, List<Object> value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForList().rightPushAll(key, value); redisTemplate.opsForList().rightPushAll(key, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -614,9 +579,8 @@ public class RedisUtils {
* @return * @return
*/ */
public boolean lSet(String key, List<Object> value, long time) { public boolean lSet(String key, List<Object> value, long time) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForList().rightPushAll(key, value); redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) { if (time > 0) {
expire(key, time); expire(key, time);
} }
@ -635,9 +599,8 @@ public class RedisUtils {
* @return / * @return /
*/ */
public boolean lUpdateIndex(String key, long index, Object value) { public boolean lUpdateIndex(String key, long index, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
stringRedisTemplate.opsForList().set(key, index, value); redisTemplate.opsForList().set(key, index, value);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -653,9 +616,8 @@ public class RedisUtils {
* @return 移除的个数 * @return 移除的个数
*/ */
public long lRemove(String key, long count, Object value) { public long lRemove(String key, long count, Object value) {
key = StrUtil.format("{}_{}",TenantContextHolder.getTenantId(),key);
try { try {
return stringRedisTemplate.opsForList().remove(key, count, value); return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return 0; return 0;

Loading…
Cancel
Save