Java 序列化外部库
我在我们的一个项目中使用了Java 序列化外部库,java,serialization,redis,Java,Serialization,Redis,我在我们的一个项目中使用了Redis。虽然我意识到Redis需要序列化对象才能持久化,但我想了解在我的例子中如何处理一些引用外部库类(StandardServleteEnvironment),哪一个没有实现可序列化的,我们也不能修改它?在这种情况下,我得到的是notserializableeexception。如果您想在redis中存储用户定义的Java对象,序列化是合适的选择。然而,当您使用Java本机序列化时,它会带来一些您所面临的缺点,而且速度太慢。我也面临着同样的问题,经过长时间的搜索,
Redis
。虽然我意识到Redis需要序列化对象才能持久化,但我想了解在我的例子中如何处理一些引用外部库类(StandardServleteEnvironment)
,哪一个没有实现可序列化的,我们也不能修改它?在这种情况下,我得到的是notserializableeexception
。如果您想在redis中存储用户定义的Java对象,序列化是合适的选择。然而,当您使用Java本机序列化时,它会带来一些您所面临的缺点,而且速度太慢。我也面临着同样的问题,经过长时间的搜索,我找到了使用的解决方案
附言:如果你不想使用kryo和java内置序列化,那么创建serializable类并将你的对象传递给这个类,然后完成你的工作
我希望这对你有帮助 如Praga所述,kyro是不实现可序列化接口的对象(反)序列化的良好解决方案。以下是kyro序列化的示例代码,希望对您有所帮助:
Kryo kryo = new Kryo();
private byte[] encode(Object obj) {
ByteArrayOutputStream objStream = new ByteArrayOutputStream();
Output objOutput = new Output(objStream);
kryo.writeClassAndObject(objOutput, obj);
objOutput.close();
return objStream.toByteArray();
}
private <T> T decode(byte[] bytes) {
return (T) kryo.readClassAndObject(new Input(bytes));
}
Kryo Kryo=new Kryo();
专用字节[]编码(对象obj){
ByteArrayOutputStream objStream=新建ByteArrayOutputStream();
输出对象输出=新输出(对象流);
kryo.writeClassAndObject(objOutput,obj);
objOutput.close();
返回objStream.toByteArray();
}
专用T解码(字节[]字节){
返回(T)kryo.readClassAndObject(新输入(字节));
}
Maven依赖项:
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>4.0.1</version>
</dependency>
com.estericsoftware
克鲁约
4.0.1
全面实施redis集成: 再贴现接口:
public class RedisInterface {
static final Logger logger = LoggerFactory.getLogger(RedisInterface.class);
private static RedisInterface instance =null;
public static RedisInterface getInstance ()
{
if(instance ==null)
createInstance();
return instance ;
}
private static synchronized void createInstance()
{
if(instance ==null)//in case of multi thread instances
instance =new RedisInterface();
}
JedisConfig jedis = new JedisConfig();
public boolean setAttribute(String key, Object value)
{
return this.setAttribute(key, key, value);
}
public boolean setAttribute(String key, Object value, int expireSeconds)
{
return this.setAttribute(key, key, value, expireSeconds);
}
public boolean setAttribute(String key, String field, Object value)
{
int expireSeconds = 20 *60; //20 minutes
return this.setAttribute(key, field, value, expireSeconds);
}
public boolean setAttribute(String key, String field, Object value, int expireSeconds)
{
try
{
if(key==null || "".equals(key) || field==null || "".equals(field))
return false;
byte[]keyBytes = key.getBytes();
byte[]fieldBytes = field.getBytes();
byte []valueBytes = encode(value);
long start = new Date().getTime();
jedis.set(keyBytes, fieldBytes, valueBytes, expireSeconds);
long end = new Date().getTime();
long waitTime =end-start;
logger.info("{} key saved to redis in {} milliseconds with timeout: {} seconds", new Object[] {key, waitTime, expireSeconds} );
return true;
}
catch(Exception e)
{
logger.error( "error on saving object to redis. key: " + key, e);
return false;
}
}
public <T> T getAttribute(String key)
{
return this.getAttribute(key, key);
}
public <T> T getAttribute(String key, String field)
{
try
{
if(key==null || "".equals(key) || field==null || "".equals(field)) return null;
byte[]keyBytes = key.getBytes();
byte[]fieldBytes = field.getBytes();
long start = new Date().getTime();
byte[] valueBytes = jedis.get(keyBytes, fieldBytes);
T o =null;
if(valueBytes!=null && valueBytes.length>0)
o = decode(valueBytes);
long end = new Date().getTime();
long waitTime =end-start;
logger.info("{} key read operation from redis in {} milliseconds. key found?: {}", new Object[] {key, waitTime, (o!=null)});
return o;
}
catch (Exception e)
{
logger.error( "error on getting object from redis. key: "+ key, e);
return null;
}
}
Kryo kryo = new Kryo();
private byte[] encode(Object obj) {
ByteArrayOutputStream objStream = new ByteArrayOutputStream();
Output objOutput = new Output(objStream);
kryo.writeClassAndObject(objOutput, obj);
objOutput.close();
return objStream.toByteArray();
}
private <T> T decode(byte[] bytes) {
return (T) kryo.readClassAndObject(new Input(bytes));
}
public class JedisConfig implements Closeable
{
private Pool<Jedis> jedisPool = null;
private synchronized void initializePool()
{
if(jedisPool!=null) return;
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(Integer.parseInt(Config.REDIS_MAX_ACTIVE_CONN)); // maximum active connections
poolConfig.setMaxIdle(Integer.parseInt(Config.REDIS_MAX_IDLE_CONN)); // maximum idle connections
poolConfig.setMaxWaitMillis(Long.parseLong(Config.REDIS_MAX_WAIT_MILLIS)); // max wait time for new connection (before throwing an exception)
if("true".equals(Config.REDIS_SENTINEL_ACTIVE))
{
String [] sentinelsArray = Config.REDIS_SENTINEL_HOST_LIST.split(",");
Set<String> sentinels = new HashSet();
for(String sentinel : sentinelsArray)
{
sentinels.add(sentinel);
}
String masterName = Config.REDIS_SENTINEL_MASTER_NAME;
jedisPool = new JedisSentinelPool(masterName, sentinels, poolConfig, Integer.parseInt(Config.REDIS_CONN_TIMEOUT));
}
else
{
jedisPool = new JedisPool(poolConfig,
Config.REDIS_IP,
Integer.parseInt(Config.REDIS_PORT),
Integer.parseInt(Config.REDIS_CONN_TIMEOUT));
}
}
protected Jedis getJedis()
{
if(jedisPool==null)
initializePool();
Jedis jedis = jedisPool.getResource();
return jedis;
}
public Long set(final byte[] key, final byte[] field, final byte[] value, int expireSeconds)
{
Jedis redis = null;
Long ret =0L;
try
{
redis = getJedis();
ret = redis.hset(key, field, value);
redis.expire(key, expireSeconds);
}
finally
{
if(redis!=null)
redis.close();
}
return ret;
}
public byte[] get(final byte[] key, final byte[] field) {
Jedis redis = null ;
byte[] valueBytes = null;
try
{
redis = getJedis();
valueBytes = redis.hget(key, field);
}
finally
{
if(redis!=null)
redis.close();
}
return valueBytes;
}
@Override
public void close() throws IOException {
if(jedisPool!=null)
jedisPool.close();
}
公共类接口{
静态最终记录器Logger=LoggerFactory.getLogger(RedisInterface.class);
私有静态接口实例=null;
公共静态接口getInstance()
{
if(实例==null)
createInstance();
返回实例;
}
私有静态同步void createInstance()
{
if(instance==null)//如果是多线程实例
实例=新接口();
}
绝地武士=新绝地武士();
公共布尔setAttribute(字符串键、对象值)
{
返回此.setAttribute(键、键、值);
}
公共布尔setAttribute(字符串键、对象值、int expireSeconds)
{
返回此.setAttribute(key、key、value、expireSeconds);
}
公共布尔setAttribute(字符串键、字符串字段、对象值)
{
int expireSeconds=20*60;//20分钟
返回此.setAttribute(键、字段、值、过期秒);
}
公共布尔setAttribute(字符串键、字符串字段、对象值、int expireSeconds)
{
尝试
{
如果(键==null | |?“”.equals(键)| |字段==null | |?“”.equals(字段))
返回false;
byte[]keyBytes=key.getBytes();
byte[]fieldBytes=field.getBytes();
字节[]值字节=编码(值);
长启动=新日期().getTime();
设置(keyBytes、fieldBytes、valueBytes、expireSeconds);
long end=new Date().getTime();
长等待时间=结束-开始;
info(“{}毫秒内保存到redis的{}键,超时:{}秒”,新对象[]{key,waitTime,expireSeconds});
返回true;
}
捕获(例外e)
{
logger.error(“将对象保存到redis.key时出错:“+key,e”);
返回false;
}
}
公共gett属性(字符串键)
{
返回此.getAttribute(key,key);
}
public T getAttribute(字符串键、字符串字段)
{
尝试
{
如果(key==null | |“”.equals(key)| | field==null | |“”.equals(field))返回null;
byte[]keyBytes=key.getBytes();
byte[]fieldBytes=field.getBytes();
长启动=新日期().getTime();
byte[]valueBytes=jedis.get(keyBytes,fieldBytes);
T o=零;
if(valueBytes!=null&&valueBytes.length>0)
o=解码(valueBytes);
long end=new Date().getTime();
长等待时间=结束-开始;
logger.info(“{}毫秒内从redis读取{}键的操作。找到的键?:{}”,新对象[]{key,waitTime,(o!=null)});
返回o;
}
捕获(例外e)
{
logger.error(“从redis.key获取对象时出错:“+key,e”);
返回null;
}
}
Kryo Kryo=新Kryo();
专用字节[]编码(对象obj){
ByteArrayOutputStream objStream=新建ByteArrayOutputStream();
输出对象输出=新输出(对象流);
kryo.writeClassAndObject(objOutput,obj);
objOutput.close();
返回objStream.toByteArray();
}
专用T解码(字节[]字节){
返回(T)kryo.readClassAndObject(新输入(字节));
}
}
绝地配置:
public class RedisInterface {
static final Logger logger = LoggerFactory.getLogger(RedisInterface.class);
private static RedisInterface instance =null;
public static RedisInterface getInstance ()
{
if(instance ==null)
createInstance();
return instance ;
}
private static synchronized void createInstance()
{
if(instance ==null)//in case of multi thread instances
instance =new RedisInterface();
}
JedisConfig jedis = new JedisConfig();
public boolean setAttribute(String key, Object value)
{
return this.setAttribute(key, key, value);
}
public boolean setAttribute(String key, Object value, int expireSeconds)
{
return this.setAttribute(key, key, value, expireSeconds);
}
public boolean setAttribute(String key, String field, Object value)
{
int expireSeconds = 20 *60; //20 minutes
return this.setAttribute(key, field, value, expireSeconds);
}
public boolean setAttribute(String key, String field, Object value, int expireSeconds)
{
try
{
if(key==null || "".equals(key) || field==null || "".equals(field))
return false;
byte[]keyBytes = key.getBytes();
byte[]fieldBytes = field.getBytes();
byte []valueBytes = encode(value);
long start = new Date().getTime();
jedis.set(keyBytes, fieldBytes, valueBytes, expireSeconds);
long end = new Date().getTime();
long waitTime =end-start;
logger.info("{} key saved to redis in {} milliseconds with timeout: {} seconds", new Object[] {key, waitTime, expireSeconds} );
return true;
}
catch(Exception e)
{
logger.error( "error on saving object to redis. key: " + key, e);
return false;
}
}
public <T> T getAttribute(String key)
{
return this.getAttribute(key, key);
}
public <T> T getAttribute(String key, String field)
{
try
{
if(key==null || "".equals(key) || field==null || "".equals(field)) return null;
byte[]keyBytes = key.getBytes();
byte[]fieldBytes = field.getBytes();
long start = new Date().getTime();
byte[] valueBytes = jedis.get(keyBytes, fieldBytes);
T o =null;
if(valueBytes!=null && valueBytes.length>0)
o = decode(valueBytes);
long end = new Date().getTime();
long waitTime =end-start;
logger.info("{} key read operation from redis in {} milliseconds. key found?: {}", new Object[] {key, waitTime, (o!=null)});
return o;
}
catch (Exception e)
{
logger.error( "error on getting object from redis. key: "+ key, e);
return null;
}
}
Kryo kryo = new Kryo();
private byte[] encode(Object obj) {
ByteArrayOutputStream objStream = new ByteArrayOutputStream();
Output objOutput = new Output(objStream);
kryo.writeClassAndObject(objOutput, obj);
objOutput.close();
return objStream.toByteArray();
}
private <T> T decode(byte[] bytes) {
return (T) kryo.readClassAndObject(new Input(bytes));
}
public class JedisConfig implements Closeable
{
private Pool<Jedis> jedisPool = null;
private synchronized void initializePool()
{
if(jedisPool!=null) return;
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(Integer.parseInt(Config.REDIS_MAX_ACTIVE_CONN)); // maximum active connections
poolConfig.setMaxIdle(Integer.parseInt(Config.REDIS_MAX_IDLE_CONN)); // maximum idle connections
poolConfig.setMaxWaitMillis(Long.parseLong(Config.REDIS_MAX_WAIT_MILLIS)); // max wait time for new connection (before throwing an exception)
if("true".equals(Config.REDIS_SENTINEL_ACTIVE))
{
String [] sentinelsArray = Config.REDIS_SENTINEL_HOST_LIST.split(",");
Set<String> sentinels = new HashSet();
for(String sentinel : sentinelsArray)
{
sentinels.add(sentinel);
}
String masterName = Config.REDIS_SENTINEL_MASTER_NAME;
jedisPool = new JedisSentinelPool(masterName, sentinels, poolConfig, Integer.parseInt(Config.REDIS_CONN_TIMEOUT));
}
else
{
jedisPool = new JedisPool(poolConfig,
Config.REDIS_IP,
Integer.parseInt(Config.REDIS_PORT),
Integer.parseInt(Config.REDIS_CONN_TIMEOUT));
}
}
protected Jedis getJedis()
{
if(jedisPool==null)
initializePool();
Jedis jedis = jedisPool.getResource();
return jedis;
}
public Long set(final byte[] key, final byte[] field, final byte[] value, int expireSeconds)
{
Jedis redis = null;
Long ret =0L;
try
{
redis = getJedis();
ret = redis.hset(key, field, value);
redis.expire(key, expireSeconds);
}
finally
{
if(redis!=null)
redis.close();
}
return ret;
}
public byte[] get(final byte[] key, final byte[] field) {
Jedis redis = null ;
byte[] valueBytes = null;
try
{
redis = getJedis();
valueBytes = redis.hget(key, field);
}
finally
{
if(redis!=null)
redis.close();
}
return valueBytes;
}
@Override
public void close() throws IOException {
if(jedisPool!=null)
jedisPool.close();
}
public类JedisConfig实现了Closeable
{
私有池=空;
私有同步的void initializePool()
{
如果(0!=null)返回;
JedisPoolConfig poolConfig=新的JedisPoolConfig();
poolConfig.setMaxTotal(Integer.parseInt(Config.REDIS\u MAX\u ACTIVE\u CONN));//最大活动连接数
poolConfig.setMaxIdle(Integer.parseInt(Config.REDIS\u MAX\u IDLE\u CONN));//最大空闲连接数
poolConfig.setMaxWaitMillis(Long.parseLong(Config.REDIS_MAX_WAIT_MILLIS));//新连接的最大等待时间(在引发异常之前)
if(“true”.equals(Config.REDIS\u SENTINEL\u ACTIVE))
{
字符串[]sentinelsArray=Config.REDIS\u SENTINEL\u HOST\u LIST.split(“,”);
Set sentinels=new HashSet();
用于(字符串sentinel:sentinelsArray)
{
哨兵。添加(哨兵);
}
字符串masterName=Config.REDIS\u SENTINEL\u MASTER\u NAME;
jedisPool=新的JedisSentinelPool(masterName、sentinel、poolConfig、Integer.parseI