猿问

redis怎么序列化

redis怎么序列化


四季花海
浏览 1157回答 1
1回答

慕的地8271018

redis序列化数据有多重方式:JacksonJsonRedisSerializerJdkSerializationRedisSerializerOxmSerializer这里前两种测试1.StringSerializer.javapublic enum StringSerializer implements RedisSerializer<String> {&nbsp; &nbsp;INSTANCE; &nbsp;&nbsp; &nbsp;public byte[] serialize(String s) throws SerializationException { &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return (null != s ? s.getBytes() : new byte[0]); &nbsp;&nbsp; &nbsp;} &nbsp;&nbsp; &nbsp;public String deserialize(byte[] bytes) throws SerializationException { &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (bytes.length > 0) { &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new String(bytes); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} else { &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return null; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;} &nbsp;&nbsp; &nbsp;} &nbsp;}12345678910111213142.测试类public RedisConnectionFactory redisConnectionFactory() { &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;JedisConnectionFactory cf = new JedisConnectionFactory(); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cf.setHostName("172.16.28.214"); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cf.setPort(6379); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;//cf.setPassword("123456"); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cf.afterPropertiesSet(); &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return cf; &nbsp;&nbsp; &nbsp;}@Test&nbsp; &nbsp;public void test() {&nbsp; &nbsp; &nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RedisConnectionFactory connectionFactory = redisConnectionFactory();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RedisTemplate<String, Serializable> redis = new RedisTemplate<String, Serializable>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;redis.setConnectionFactory(connectionFactory);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;redis.setKeySerializer(StringSerializer.INSTANCE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// redis.setValueSerializer(new JdkSerializationRedisSerializer());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;redis.setValueSerializer(new JacksonJsonRedisSerializer<TestUser>(TestUser.class));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;redis.afterPropertiesSet();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ValueOperations<String, Serializable> ops = redis.opsForValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TestUser user1 = new TestUser();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;user1.setName("lisi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;user1.setId(20L);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// ops.set("lisi", user1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TestUser user = (TestUser) ops.get("lisi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(user.getName());&nbsp; &nbsp; &nbsp; &nbsp;} catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}
随时随地看视频慕课网APP
我要回答