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. 319
      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;
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.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.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 配置类
*/
@Slf4j
public class YudaoRedisAutoConfiguration extends CachingConfigurerSupport {
@Configuration
public class YudaoRedisAutoConfiguration {
/**
* 创建 RedisTemplate Bean使用 JSON 序列化方式
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
// 创建 RedisTemplate 对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
//序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
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);
}
// @Bean
// public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
// // 创建 RedisTemplate 对象
// RedisTemplate<String, Object> template = new RedisTemplate<>();
// // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。
// template.setConnectionFactory(factory);
// // 使用 String 序列化方式,序列化 KEY 。
// template.setKeySerializer(RedisSerializer.string());
// template.setHashKeySerializer(RedisSerializer.string());
// // 使用 JSON 序列化方式(库是 Jackson ),序列化 VALUE 。
// template.setValueSerializer(RedisSerializer.json());
// template.setHashValueSerializer(RedisSerializer.json());
// return template;
// }
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
// httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
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;
import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest;
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.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.service.auth.MemberAuthServiceImpl;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.function.Consumer;
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.randomString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.when;
// TODO @芋艿:单测的 review,等逻辑都达成一致后
/**
* {@link MemberUserServiceImpl} 的单元测试类
*
* @author 宋天
*/
@Import({MemberUserServiceImpl.class, YudaoRedisAutoConfiguration.class})
public class MemberUserServiceImplTest extends BaseDbAndRedisUnitTest {
@Resource
private MemberUserServiceImpl memberUserService;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private MemberUserMapper userMapper;
@MockBean
private MemberAuthServiceImpl authService;
@MockBean
private PasswordEncoder passwordEncoder;
@MockBean
private SmsCodeApi smsCodeApi;
@MockBean
private FileApi fileApi;
@Test
public void testUpdateNickName_success(){
// mock 数据
MemberUserDO userDO = randomUserDO();
userMapper.insert(userDO);
// 随机昵称
String newNickName = randomString();
// 调用接口修改昵称
memberUserService.updateUserNickname(userDO.getId(),newNickName);
// 查询新修改后的昵称
String nickname = memberUserService.getUser(userDO.getId()).getNickname();
// 断言
assertEquals(newNickName,nickname);
}
@Test
public void testUpdateAvatar_success() throws Exception {
// mock 数据
MemberUserDO dbUser = randomUserDO();
userMapper.insert(dbUser);
// 准备参数
Long userId = dbUser.getId();
byte[] avatarFileBytes = randomBytes(10);
ByteArrayInputStream avatarFile = new ByteArrayInputStream(avatarFileBytes);
// mock 方法
String avatar = randomString();
when(fileApi.createFile(eq(avatarFileBytes))).thenReturn(avatar);
// 调用
String str = memberUserService.updateUserAvatar(userId, avatarFile);
// 断言
assertEquals(avatar, str);
}
@Test
public void updateMobile_success(){
// mock数据
String oldMobile = randomNumbers(11);
MemberUserDO userDO = randomUserDO();
userDO.setMobile(oldMobile);
userMapper.insert(userDO);
// TODO 芋艿:需要修复该单元测试,重构多模块带来的
// 旧手机和旧验证码
// SmsCodeDO codeDO = new SmsCodeDO();
String oldCode = RandomUtil.randomString(4);
// codeDO.setMobile(userDO.getMobile());
// codeDO.setCode(oldCode);
// codeDO.setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene());
// codeDO.setUsed(Boolean.FALSE);
// when(smsCodeService.checkCodeIsExpired(codeDO.getMobile(),codeDO.getCode(),codeDO.getScene())).thenReturn(codeDO);
// 更新手机号
String newMobile = randomNumbers(11);
String newCode = randomNumbers(4);
AppUserUpdateMobileReqVO reqVO = new AppUserUpdateMobileReqVO();
reqVO.setMobile(newMobile);
reqVO.setCode(newCode);
reqVO.setOldMobile(oldMobile);
reqVO.setOldCode(oldCode);
memberUserService.updateUserMobile(userDO.getId(),reqVO);
assertEquals(memberUserService.getUser(userDO.getId()).getMobile(),newMobile);
}
// ========== 随机对象 ==========
@SafeVarargs
private static MemberUserDO randomUserDO(Consumer<MemberUserDO>... consumers) {
Consumer<MemberUserDO> consumer = (o) -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
};
return randomPojo(MemberUserDO.class, ArrayUtils.append(consumer, consumers));
}
}
//package cn.iocoder.yudao.module.member.service.user;
//
//import cn.hutool.core.util.RandomUtil;
//import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
//import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
//import cn.iocoder.yudao.framework.redis.config.YudaoRedisAutoConfiguration;
//import cn.iocoder.yudao.framework.test.core.ut.BaseDbAndRedisUnitTest;
//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.dal.dataobject.user.MemberUserDO;
//import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
//import cn.iocoder.yudao.module.member.service.auth.MemberAuthServiceImpl;
//import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
//import org.junit.jupiter.api.Test;
//import org.springframework.boot.test.mock.mockito.MockBean;
//import org.springframework.context.annotation.Import;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.security.crypto.password.PasswordEncoder;
//
//import javax.annotation.Resource;
//import java.io.ByteArrayInputStream;
//import java.util.function.Consumer;
//
//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.randomString;
//import static org.junit.jupiter.api.Assertions.assertEquals;
//import static org.mockito.Mockito.eq;
//import static org.mockito.Mockito.when;
//
//// TODO @芋艿:单测的 review,等逻辑都达成一致后
///**
// * {@link MemberUserServiceImpl} 的单元测试类
// *
// * @author 宋天
// */
//@Import({MemberUserServiceImpl.class, YudaoRedisAutoConfiguration.class})
//public class MemberUserServiceImplTest extends BaseDbAndRedisUnitTest {
//
// @Resource
// private MemberUserServiceImpl memberUserService;
//
// @Resource
// private StringRedisTemplate stringRedisTemplate;
//
// @Resource
// private MemberUserMapper userMapper;
//
// @MockBean
// private MemberAuthServiceImpl authService;
//
// @MockBean
// private PasswordEncoder passwordEncoder;
//
// @MockBean
// private SmsCodeApi smsCodeApi;
// @MockBean
// private FileApi fileApi;
//
// @Test
// public void testUpdateNickName_success(){
// // mock 数据
// MemberUserDO userDO = randomUserDO();
// userMapper.insert(userDO);
//
// // 随机昵称
// String newNickName = randomString();
//
// // 调用接口修改昵称
// memberUserService.updateUserNickname(userDO.getId(),newNickName);
// // 查询新修改后的昵称
// String nickname = memberUserService.getUser(userDO.getId()).getNickname();
// // 断言
// assertEquals(newNickName,nickname);
// }
//
// @Test
// public void testUpdateAvatar_success() throws Exception {
// // mock 数据
// MemberUserDO dbUser = randomUserDO();
// userMapper.insert(dbUser);
//
// // 准备参数
// Long userId = dbUser.getId();
// byte[] avatarFileBytes = randomBytes(10);
// ByteArrayInputStream avatarFile = new ByteArrayInputStream(avatarFileBytes);
// // mock 方法
// String avatar = randomString();
// when(fileApi.createFile(eq(avatarFileBytes))).thenReturn(avatar);
// // 调用
// String str = memberUserService.updateUserAvatar(userId, avatarFile);
// // 断言
// assertEquals(avatar, str);
// }
//
// @Test
// public void updateMobile_success(){
// // mock数据
// String oldMobile = randomNumbers(11);
// MemberUserDO userDO = randomUserDO();
// userDO.setMobile(oldMobile);
// userMapper.insert(userDO);
//
// // TODO 芋艿:需要修复该单元测试,重构多模块带来的
// // 旧手机和旧验证码
//// SmsCodeDO codeDO = new SmsCodeDO();
// String oldCode = RandomUtil.randomString(4);
//// codeDO.setMobile(userDO.getMobile());
//// codeDO.setCode(oldCode);
//// codeDO.setScene(SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene());
//// codeDO.setUsed(Boolean.FALSE);
//// when(smsCodeService.checkCodeIsExpired(codeDO.getMobile(),codeDO.getCode(),codeDO.getScene())).thenReturn(codeDO);
//
// // 更新手机号
// String newMobile = randomNumbers(11);
// String newCode = randomNumbers(4);
// AppUserUpdateMobileReqVO reqVO = new AppUserUpdateMobileReqVO();
// reqVO.setMobile(newMobile);
// reqVO.setCode(newCode);
// reqVO.setOldMobile(oldMobile);
// reqVO.setOldCode(oldCode);
// memberUserService.updateUserMobile(userDO.getId(),reqVO);
//
// assertEquals(memberUserService.getUser(userDO.getId()).getMobile(),newMobile);
// }
//
// // ========== 随机对象 ==========
//
// @SafeVarargs
// private static MemberUserDO randomUserDO(Consumer<MemberUserDO>... consumers) {
// Consumer<MemberUserDO> consumer = (o) -> {
// o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
// };
// 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) {
log.info("map:{}",map);
Integer uid = map.get("uid").asInt();
Integer scope = map.get("scope").asInt();
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);
}
};
}
}

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

@ -1,205 +1,118 @@
///**
// * Copyright (C) 2018-2022
// * All rights reserved, Designed By www.yixiang.co
//
// */
//package co.yixiang.config;
//
//import cn.hutool.core.lang.Assert;
//import co.yixiang.utils.StringUtils;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.parser.ParserConfig;
//import com.alibaba.fastjson.serializer.SerializerFeature;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.codec.digest.DigestUtils;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
//import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.cache.Cache;
//import org.springframework.cache.annotation.CachingConfigurerSupport;
//import org.springframework.cache.annotation.EnableCaching;
//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 org.springframework.data.redis.cache.RedisCacheConfiguration;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisOperations;
//import org.springframework.data.redis.core.RedisTemplate;
//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.time.Duration;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author Zheng Jie
// * @date 2018-11-24
// */
//@Slf4j
//@Configuration(proxyBeanMethods = false)
//@EnableCaching
//@ConditionalOnClass(RedisOperations.class)
/**
* Copyright (C) 2018-2022
* All rights reserved, Designed By www.yixiang.co
*/
package co.yixiang.config;
import cn.hutool.core.lang.Assert;
import co.yixiang.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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 org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
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.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
* @author Zheng Jie
* @date 2018-11-24
*/
@Slf4j
@Configuration
//@EnableConfigurationProperties(RedisProperties.class)
//public class RedisConfig extends CachingConfigurerSupport {
//
// /**
// * 设置 redis 数据默认过期时间,默认2小时
// * 设置@cacheable 序列化方式
// */
// @Bean
// public RedisCacheConfiguration redisCacheConfiguration(){
// FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
// configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2));
// return configuration;
// }
//
// @SuppressWarnings("all")
// @Bean(name = "redisTemplate")
public class RedisConfig {
/**
* 设置 redis 数据默认过期时间默认2小时
* 设置@cacheable 序列化方式
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(){
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2));
return configuration;
}
@Bean(name = "redisTemplate")
// @ConditionalOnMissingBean(name = "redisTemplate")
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate<Object, Object> template = new RedisTemplate<>();
// //序列化
// FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// // value值的序列化采用fastJsonRedisSerializer
// template.setValueSerializer(fastJsonRedisSerializer);
// template.setHashValueSerializer(fastJsonRedisSerializer);
// // 全局开启AutoType,这里方便开发,使用全局的方式
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// // 建议使用这种方式,小范围指定白名单
// // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// // key的序列化采用StringRedisSerializer
// template.setKeySerializer(new StringRedisSerializer());
// template.setHashKeySerializer(new StringRedisSerializer());
// template.setConnectionFactory(redisConnectionFactory);
// 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 = 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);
// }
// };
// }
//
//}
//
///**
// * 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);
// }
//}
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//序列化
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType,这里方便开发,使用全局的方式
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringKeyRedisSerializer());
template.setHashKeySerializer(new StringKeyRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
/**
* 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);
}
}

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 = "砍价产品名称")
private String storeName;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "砍价金额")
private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "砍价商品最低价")
private BigDecimal minPrice;
@ApiModelProperty(value = "每次购买的砍价产品数量")
private Integer num;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "用户每次砍价的最大金额")
private BigDecimal bargainMaxPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "用户每次砍价的最小金额")
private BigDecimal bargainMinPrice;
@ -90,14 +90,14 @@ public class YxStoreBargainQueryVo implements Serializable {
@ApiModelProperty(value = "砍价活动简介")
private String info;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "成本价")
private BigDecimal cost;
@ApiModelProperty(value = "排序")
private Integer sort;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "邮费")
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 = "简介")
private String info;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "价格")
private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "商品价格")
private BigDecimal productPrice;
@ -82,7 +82,7 @@ public class YxStoreCombinationQueryVo implements Serializable {
@ApiModelProperty(value = "是否包邮1是0否")
private Integer isPostage;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "邮费")
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 = "价格")
private BigDecimal price;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "成本")
private BigDecimal cost;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
@ApiModelProperty(value = "原价")
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;
@ApiModelProperty(value = "成本价")
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
private Double costPrice;
@ApiModelProperty(value = "真实价格")
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
private Double truePrice;
@ApiModelProperty(value = "真实库存")
private Integer trueStock;
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
@ApiModelProperty(value = "vip真实价格")
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
public class PriceGroupDto {
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal costPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal storeFreePostage;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal storePostage;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal totalPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal vipPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
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
public class ComputeVo implements Serializable {
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal couponPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal deductionPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payPostage;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal payPrice;
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal totalPrice;
private Double usedIntegral; //使用了多少积分
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
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
public class OrderDataVo implements Serializable {
private Integer count;
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
private Double price;
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 = "属性金额")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price;
/** 拼团属性对应的金额 */
@ApiModelProperty(value = "拼团属性对应的金额")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal pinkPrice;
/** 秒杀属性对应的金额 */
@ApiModelProperty(value = "秒杀属性对应的金额")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal seckillPrice;
/** 图片 */
@ -94,7 +94,7 @@ public class YxStoreProductAttrValue implements Serializable {
/** 成本价 */
@ApiModelProperty(value = "成本价")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
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;
@ApiModelProperty(value = "商品价格")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal price;
@ApiModelProperty(value = "会员价格")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal vipPrice;
@ApiModelProperty(value = "市场价")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal otPrice;
@ApiModelProperty(value = "邮费")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal postage;
@ApiModelProperty(value = "单位名")
@ -114,7 +114,7 @@ public class YxStoreProductQueryVo implements Serializable {
private Integer isPostage;
@ApiModelProperty(value = "成本价")
//@JsonSerialize(using = BigDecimalSerializer.class)
@JsonSerialize(using = BigDecimalSerializer.class)
private BigDecimal cost;
@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;
@ApiModelProperty(value = "原价")
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
private Double otPrice;
@ApiModelProperty(value = "父ID")
private Integer pid;
@ApiModelProperty(value = "产品价格")
//@JsonSerialize(using = DoubleSerializer.class)
@JsonSerialize(using = DoubleSerializer.class)
private Double price;
@ApiModelProperty(value = "产品销量")

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

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

Loading…
Cancel
Save