- Fastjson2 Serialization
- Difference between fastjson and fastjson2
Spring Data Redis provides us with the followingSerializer:GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
Comparison of serialization methods:
- JdkSerializationRedisSerializer: uses the serialization functionality provided by the JDK. The advantage is that deserialization does not need to provide type information (class), but the disadvantage is that you need to implement the Serializable interface , there are also serialized results are very large , is about 5 times the JSON format , which will consume a lot of memory redis server .
- Jackson2JsonRedisSerializer: Use the Jackson library to serialize objects to JSON strings. The advantage is that the speed is fast, the serialized string is short and concise, do not need to implement the Serializable interface. But the disadvantages are also very fatal, that is, this type of constructor has a type parameter , you must provide the type of object to be serialized information (.class object). By looking at the source code, found that it is only in the deserialization process used in the type information.
Use FastJson2 for this. Rewrite some serializers and implement the RedisSerializer interface. The source code is below:
<dependency>
<groupId>.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.50</version>
</dependency>
Fastjson2 Serialization
FastJson2JsonRedisSerializer
package ;
import .;
import .;
import .;
import .;
import ;
import ;
import ;
/**
* RedisutilizationFastJsonserialize
*
* @author ruoyi
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{
/**
* automatic recognitionjsonObject Whitelist Configuration(Only package names that are allowed to be parsed,The smaller the range, the safer.)
*/
public static final String[] JSON_WHITELIST_STR = { "", "" };
public static final Charset DEFAULT_CHARSET = ("UTF-8");
static final Filter AUTO_TYPE_FILTER = (JSON_WHITELIST_STR);
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz)
{
super();
= clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null)
{
return new byte[0];
}
return (t, ).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || <= 0)
{
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T)(str, clazz, AUTO_TYPE_FILTER);
}
}
package ;
import .FastJson2JsonRedisSerializer ;import ;FastJson2JsonRedisSerializer ;import .
import ;
import ;
import ;
import ;
import ;
import ;
@EnableCaching //Enable caching, either on the cache configuration class or on the springboot startup class.
@Configuration
public class RedisConfig {
/**
* Creates a RedisTemplate instance for manipulating the Redis database.
* Where redisTemplate is a template object generalized as <String, Object> that stores key-value pair data;
* @param factory factory is a Redis connection factory object, used to establish a connection to the Redis server
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<> ();
(factory).
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer();
// Use the StringRedisSerializer to serialize and deserialize redis key values.
(new StringRedisSerializer()); // Use StringRedisSerializer to serialize and deserialize redis key values.
(serializer).
// The key of the hash is also serialized using StringRedisSerializer
(new StringRedisSerializer()); (serializer); // Hash's key is also serialized using StringRedisSerializer.
(serializer);
();
return template.
}
}
package ;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* judgementskeywhether or not
*
* @param key linchpin
* @return true remain false不remain
*/
public boolean hasKey(String key) {
return (key);
}
/**
* Specify the cache expiration time
*
* @param key linchpin
* @param time timing(unit of angle or arc equivalent one sixtieth of a degree)
*/
public boolean expire(String key, long time) {
try {
(key, time, );
return true;
} catch (Exception ex) {
();
}
return false;
}
/**
* gain Keys
*
* @param key linchpin
*/
public Set<String> keys(String key) {
Set<String> result = new HashSet();
try {
result = (key);
} catch (Exception ex) {
();
}
return result;
}
/**
* Delete Cache
*/
public boolean del(String key) {
try {
(key);
return true;
} catch (Exception ex) {
();
}
return false;
}
/**
* Delete Cache
*/
public boolean del(Collection<String> keys) {
try {
(keys);
return true;
} catch (Exception ex) {
();
}
return false;
}
//region String
public <T> T get(String key) {
ValueOperations<String, T> operation = ();
return (key);
}
public <T> boolean set(String key, T value) {
try {
().set(key, value);
return true;
} catch (Exception ex) {
();
}
return false;
}
/**
* 普通缓存放入并设置timing
*
* @param key linchpin
* @param value (be) worth
* @param time timing(subspecies) timegreater than0 in the event thattimeless than or equal to0 An indefinite period will be set
* @return truesuccesses false fail (e.g. experiments)
*/
public boolean set(String key, Object value, long time) {
try {
().set(key, value, time, );
return true;
} catch (Exception ex) {
();
}
return false;
}
//endregion
//region Hash
public <T> T hget(String key, String hashKey) {
HashOperations<String, String, T> hash = ();
return (key, hashKey);
}
public <T> Map<String, T> hmget(String key) {
return ().entries(key);
}
/**
* To a sheet ofhashPutting data in the table,in the event that不remaincommander-in-chief (military)创建
*
* @param key linchpin
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc
* @param value (be) worth
* @return true successes falsefail (e.g. experiments)
*/
public boolean hset(String key, String hashKey, Object value) {
().put(key, hashKey, value);
return true;
}
/**
* To a sheet ofhashPutting data in the table,in the event that不remaincommander-in-chief (military)创建
*
* @param key linchpin
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc
* @param value (be) worth
* @param time timing(minutes) take note of:in the event that已remain的hash表有timing,这里commander-in-chief (military)会替换原有的timing
* @return true successes falsefail (e.g. experiments)
*/
public boolean hset(String key, String hashKey, Object value, long time) {
().put(key, hashKey, value);
if (time > 0) {
(key, time, );
}
return true;
}
/**
* HashSet
*
* @param key linchpin
* @param map 对应多个linchpin(be) worth
* @return true successes false fail (e.g. experiments)
*/
public boolean hmset(String key, Map<String, Object> map) {
().putAll(key, map);
return true;
}
/**
* HashSet 并设置timing
*
* @param key linchpin
* @param map 对应多个linchpin(be) worth
* @param time timing(unit of angle or arc equivalent one sixtieth of a degree)
* @return truesuccesses falsefail (e.g. experiments)
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
().putAll(key, map);
if (time > 0) {
(key, time, );
}
return true;
}
/**
* removinghash表中的(be) worth
*
* @param key linchpin cannot benull
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc It is possible to make multiple cannot benull
*/
public void hdel(String key, Object... hashKey) {
().delete(key, hashKey);
}
/**
* judgementshash表中是否有该classifier for principles, items, clauses, tasks, research projects etc的(be) worth
*
* @param key linchpin cannot benull
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc cannot benull
* @return true remain false不remain
*/
public boolean hHasKey(String key, String hashKey) {
return ().hasKey(key, hashKey);
}
/**
* hashin increasing order in the event that不remain,will then create a 并把新增后的(be) worth返回
*
* @param key linchpin
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc
* @param by To add a few(more than0)
* @return
*/
public double hincr(String key, String hashKey, double by) {
return ().increment(key, hashKey, by);
}
/**
* hashin descending order
*
* @param key linchpin
* @param hashKey classifier for principles, items, clauses, tasks, research projects etc
* @param by To reduce the number of notes(less than0)
* @return
*/
public double hdecr(String key, String hashKey, double by) {
return ().increment(key, hashKey, -by);
}
//endregion
//region List
/**
* gainlistThe contents of the cache
* @param key linchpin
* @param start commencement
* @param end close 0 until (a time) -1代表所有(be) worth
* @return
*/
public <T> List<T> lrange(String key, long start, long end) {
return ().range(key, start, end);
}
/**
* gainlistLength of the cache
* @param key linchpin
* @return
*/
public long llen(String key) {
return ().size(key);
}
/**
* By Indexing gainlist中的(be) worth
* @param key linchpin
* @param index indexing index>=0hour, 0 meter header,1 second element,in succession;index<0hour,-1,suffix,-2倒数second element,in succession
* @return
*/
public Object lindex(String key, long index) {
return ().index(key, index);
}
/**
* commander-in-chief (military)一个或多个(be) worth插入until (a time)列表的尾部(far right)。
* @param key linchpin
* @param value (be) worth
* @return
*/
public boolean lrpush(String key, Object value) {
().rightPush(key, value);
return true;
}
/**
* commander-in-chief (military)一个或多个(be) worth插入until (a time)列表的尾部(far right)。
* @param key linchpin
* @param value (be) worth
* @param time timing(unit of angle or arc equivalent one sixtieth of a degree)
* @return
*/
public boolean lrpush(String key, Object value, long time) {
().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* commander-in-chief (military)一个或多个(be) worth插入until (a time)列表的尾部(far right)。
* @param key linchpin
* @param value (be) worth
* @return
*/
public boolean lrpush(String key, List<Object> value) {
().rightPushAll(key, value);
return true;
}
/**
* commander-in-chief (military)listput into cache
* @param key linchpin
* @param value (be) worth
* @param time timing(unit of angle or arc equivalent one sixtieth of a degree)
* @return
*/
public boolean lrpush(String key, List<Object> value, long time) {
().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* By Indexing来设置元素的(be) worth
* @param key linchpin
* @param index indexing
* @param value (be) worth
* @return /
*/
public boolean lset(String key, long index, Object value) {
().set(key, index, value);
return true;
}
/**
* removing指定key集合中(be) worth等于valueparticular element(count=0, removing所有(be) worth等于valueparticular element; count>0, 从头部commencementremoving第一个(be) worth等于valueparticular element; count<0, 从尾部commencementremoving第一个(be) worth等于valueparticular element)
* @param key linchpin
* @param count count>0, 从头部commencementremoving第一个(be) worth等于valueparticular element; count<0, 从尾部commencementremoving第一个(be) worth等于valueparticular element
* @param value (be) worth
* @return Number of removals
*/
public long lremove(String key, long count, Object value) {
return ().remove(key, count, value);
}
//endregion
}
Difference between fastjson and fastjson2
FastJSON is a widely used JSON parsing library, and its high performance and simplicity are loved by developers. However, with the complexity of application scenarios and increased security requirements, FastJSON has gradually exposed some problems. In order to solve these problems and further improve the performance and security , Alibaba introduced FastJSON2 . the following is a detailed comparison of FastJSON and FastJSON2 :
I. Performance
FastJSON: Known for its fast and efficient , you can quickly convert Java objects to JSON strings , you can also convert JSON strings to Java objects .
FastJSON2: Various performance optimizations have been made to improve the efficiency of serialization by optimizing serialization algorithms and data structures, reducing unnecessary object creation and copy operations, thus reducing CPU and memory overhead. At the same time, the parser has been refactored so that it can handle large-scale JSON data more quickly. According to the performance test data provided by the official , FastJSON2's performance far exceeds that of other popular JSON libraries such as Jackson, Gson and .
II. Security
FastJSON: There are some vulnerabilities in security, especially its AutoType function has more prominent security issues. This function brings type information in the serialized JSON string and does not need to pass the type when deserializing to achieve automatic type recognition, but this also provides a possibility for malicious attacks.
FastJSON2: Significant security improvements have been made to address some of the security vulnerabilities exposed in previous versions. To prevent deserialization vulnerabilities, FastJSON2 introduces a stricter blacklisting mechanism, which prohibits certain dangerous types of deserialization operations by default. Meanwhile, the enhanced type detection mechanism can better prevent malicious data injection and ensure the security of data parsing. In addition, FastJSON2's AutoType feature must be explicitly turned on in order to be used and does not have any whitelisting, nor does it include any whitelisting of Exception classes, which further improves its security.
III. Functional characteristics
FastJSON: Supports the processing of complex objects , including nested objects , collections , Map , etc. ; supports annotations to specify the mapping relationship between Java objects and JSON strings ; allows the user to customize the implementation of the object serialization and deserialization process ; provides a streaming API can provide better performance when dealing with large amounts of JSON data .
FastJSON2: A series of new functional features have been added to FastJSON. For example, the support for JSONPath is more comprehensive and efficient, allowing developers to use JSONPath expressions to easily access and manipulate JSON data; improved processing of date and time, providing more configuration options and better performance, support for a variety of date formats and time zones to deal with; provides support for JSON Schema, enhancing the ability to validate the data; new Add support for the binary format JSONB , further improving the efficiency and flexibility of data processing .
IV. Compatibility
FastJSON: As an early version of the JSON processing library , has been widely used in a variety of Java projects .
FastJSON2: While maintaining compatibility with FastJSON, some necessary improvements and optimizations have been made. For example, FastJSON2 supports the latest JDK features , including JDK 11 and JDK 17 , etc.; at the same time provides optimized support for the Kotlin language , so that Kotlin developers can use FastJSON2 more conveniently. in addition , FastJSON2 also supports cross-platform compatibility , including Android 8 + and other platforms.
V. Ease of use
FastJSON: Provides a straightforward API that is very easy to use.
FastJSON2: Some APIs have been adjusted and optimized to make them more intuitive and easy to use. It also provides more detailed and friendly error messages to help developers locate and solve problems faster.
In summary, FastJSON2 has significant improvements in performance, security, functional features, compatibility and ease of use compared to FastJSON. For application scenarios that require high-performance JSON parsing and serialization, especially in the case of high security requirements, FastJSON2 is a better choice.