目录
1、RedisSerializer序列化为JSON格式的Utf-8的String格式
2、设置 RedisCache默认过期时间为1个小时
3、redis配置,设置序列化方式,缓存数据的可见行
4、缓存配置ShiroRedisConfig 实体类
5、session过期时间 如果部署多机环境,需要打开注释,30分钟
6、主要是解决JSON格式化的精度以及空数据的格式配置。JSON的序列化配置
1、RedisSerializer序列化为JSON格式的Utf-8的String格式
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* fastjson redis序列化器,可以设置Redis的序列化,一起传输数据的序列化;
* kafka序列化也需要改成JSON格式,只有这样才能够真正的实现读取转义
*
* @Date 2020/11/7 上午9:20
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
//格式转化为统一的UTF-8 这样的
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static {
//全局设置成这个
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
//如果遇到反序列化autoType is not support错误,请添加并修改一下包名到bean文件路径
// ParserConfig.getGlobalInstance().addAccept("com.xxxxx.xxx");
}
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
/***
* 重新写序列化方法,改成JSON格式,方便通信与读写
* @param t
* @return
* @throws SerializationException
*/
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
/***
* 反序列化方法,搞成统一的JSON格式,方便通信与读写
* @param bytes
* @return
* @throws SerializationException
*/
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper) {
//获取数据的时候进行判空作为最后一个拦截
Assert.notNull(objectMapper, "'objectMapper' must not be null,please check your object");
this.objectMapper = objectMapper;
}
/****
* jackson-databind-2.9.8.jar jackson进行序列化Java类型
* @param clazz
* @return
*/
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
2、设置 RedisCache默认过期时间为1个小时
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.time.Duration;
/**
* 设置 RedisCache默认过期时间为1个小时
* ehcache配置 使用ehcache 做缓存,开启注解
* @date 2021-05-20 23:11
*/
public class CacheConfig {
/**
* 缓存
* @param redisConnectionFactory
* @return
*/
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1));
// 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
}
3、redis配置,设置序列化方式,缓存数据的可见行
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置,设置序列化方式,缓存数据的可见行
* @date 2017-05-20 23:11
*/
(RedisTemplate.class)
public class RedisAutConfig{
public RedisSerializer fastJson2JsonRedisSerializer() {
return new FastJson2JsonRedisSerializer<>(Object.class);
}
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
4、缓存配置ShiroRedisConfig 实体类
/**
* pojo redis 缓存配置ShiroRedisConfig 实体类
* @date:2020/11/14
**/
(prefix = ShiroRedisConfig.PREFIX)
public class ShiroRedisConfig {
public static final String PREFIX = "shiro.redis";
private String host;
private Integer port;
private Integer database;
private String password;
private Integer timeout;
}
5、session过期时间 如果部署多机环境,需要打开注释,30分钟
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
/**
* spring session配置
* session过期时间 如果部署多机环境,需要打开注释,30分钟
* @date 2021-07-13 21:05
*/
(maxInactiveIntervalInSeconds = 1800)
(prefix = "admin", name = "spring-session-open", havingValue = "true")
public class SpringSessionConfig {
}
6、主要是解决JSON格式化的精度以及空数据的格式配置。JSON的序列化配置
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zeus.core.Serializer.BigDecimalToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
主要是解决JSON格式化的精度以及空数据的格式配置
* @date 2021-06-04
**/
("fastJsonConfig")
(com.alibaba.fastjson.JSON.class)
(FastJsonHttpMessageConverter.class)
public class FastJsonConfiguration {
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
converter.setFastJsonConfig(fastjsonConfig());
converter.setSupportedMediaTypes(getSupportedMediaType());
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
return converter;
}
/**
* fastjson的配置
*/
public FastJsonConfig fastjsonConfig() {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
// SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.BrowserCompatible
);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
// initOtherValueFilters(fastJsonConfig);
//解决Long转json精度丢失的问题
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
//serializeConfig.put(Long.class, ToStringSerializer.instance);
// serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
// serializeConfig.put(BigDecimal.class, BigDecimalToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(serializeConfig);
return fastJsonConfig;
}
/**
* 支持的mediaType类型
*/
public List<MediaType> getSupportedMediaType() {
ArrayList<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON);
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
// mediaTypes.add(MediaType.APPLICATION_ATOM_XML);
// mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
// mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
// mediaTypes.add(MediaType.APPLICATION_PDF);
// mediaTypes.add(MediaType.APPLICATION_RSS_XML);
// mediaTypes.add(MediaType.APPLICATION_XHTML_XML);
// mediaTypes.add(MediaType.APPLICATION_XML);
// mediaTypes.add(MediaType.IMAGE_GIF);
// mediaTypes.add(MediaType.IMAGE_JPEG);
// mediaTypes.add(MediaType.IMAGE_PNG);
// mediaTypes.add(MediaType.TEXT_EVENT_STREAM);
// mediaTypes.add(MediaType.TEXT_HTML);
// mediaTypes.add(MediaType.TEXT_MARKDOWN);
// mediaTypes.add(MediaType.TEXT_PLAIN);
// mediaTypes.add(MediaType.TEXT_XML);
//增加解析spring boot actuator结果的解析
mediaTypes.add(MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
return mediaTypes;
}
/**
* 初始化value过滤器
* <p>
* 默认的valueFilter是把空的字段转化为空串
*/
protected void initOtherValueFilters(FastJsonConfig fastJsonConfig) {
//为空的值转化为空串
/*ValueFilter nullValueFilter = (object, name, value) -> {
if (null == value) {
return "";
} else {
return value;
}
};
fastJsonConfig.setSerializeFilters(nullValueFilter);*/
}
}