使用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;
	}

}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值