使用kryo作为spring data redis的序列化器

kryo是个高性能的序列化器,目前无人能出其右。

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="localhost"/>
		<property name="port" value="6379"/>
		<property name="password" value="asdf"/>
		<property name="timeout" value="2000"/>
		<property name="usePool" value="true"/>
	</bean>
	
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory"/>
		<property name="defaultSerializer">
			<bean class="com.skmbw.yinlei.redis.KryoRedisSerializer"/>
		</property>
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
		</property>
	</bean>

KryoRedisSerializer实现,kryo是非线程安全的,每个现成要使用自己的kryo。

public class KryoRedisSerializer<T> implements RedisSerializer<T> {
	private Kryo kryo = new Kryo();
	
	@Override
	public byte[] serialize(Object t) throws SerializationException {
		byte[] buffer = new byte[2048];
		Output output = new Output(buffer);
		kryo.writeClassAndObject(output, t);
		return output.toBytes();
	}

	@Override
	public T deserialize(byte[] bytes) throws SerializationException {
		Input input = new Input(bytes);
		@SuppressWarnings("unchecked")
		T t = (T) kryo.readClassAndObject(input);
		return t;
	}

}


你可能感兴趣的:(redis,kryo)