memcached 序列化对象
如果是数据完全可以使用JSON方式。毕竟redis直接set、get使用起来门槛低很多。redis是没有提供专用的设置对象方法,需要自己进行改写。如果是担心JSON转对象会消耗资源的情况,这个问题需要考量几个地方,第一点:就是使用的JSON转换lib是否就会存在性能问题。第二点:就是数据的数据量级别,如果是存储百万级的大数据对象,建议采用存储序列化对象方式。如果是少量的数据级对象,或者是数据对象字段不多,还是建议采用JSON转换成String方式。毕竟redis对存储字符类型这部分优化的非常好。具体采用的方式与方法,还要看你所使用的场景。
redis序列化数据有多重方式:
jacksonjsonredisserializer
jdkserializationredisserializer
oxmserializer
这里前两种测试
1.stringserializer.java
public enum stringserializer implements redisserializer {
? ?instance; ?
? ?public byte[] serialize(string s) throws serializationexception { ?
? ? ? ?return (null != s ? s.getbytes() : new byte[0]); ?
? ?} ?
? ?public string deserialize(byte[] bytes) throws serializationexception { ?
? ? ? ?if (bytes.length > 0) { ?
? ? ? ? ? ?return new string(bytes); ?
? ? ? ?} else { ?
? ? ? ? ? ?return null; ?
? ? ? ?} ?
? ?} ?
}1234567891011121314
2.测试类
public redisconnectionfactory redisconnectionfactory() { ?
? ? ? ?jedisconnectionfactory cf = new jedisconnectionfactory(); ?
? ? ? ?cf.sethostname("172.16.28.214"); ?
? ? ? ?cf.setport(6379); ?
? ? ? ?//cf.setpassword("123456"); ?
? ? ? ?cf.afterpropertiesset(); ?
? ? ? ?return cf; ?
? ?}
@test
? ?public void test() {
? ? ? ?try {
? ? ? ? ? ?redisconnectionfactory connectionfactory = redisconnectionfactory();
? ? ? ? ? ?redistemplate redis = new redistemplate();
? ? ? ? ? ?redis.setconnectionfactory(connectionfactory);
? ? ? ? ? ?redis.setkeyserializer(stringserializer.instance);
? ? ? ? ? ?// redis.setvalueserializer(new jdkserializationredisserializer());
? ? ? ? ? ?redis.setvalueserializer(new jacksonjsonredisserializer(testuser.class));
? ? ? ? ? ?redis.afterpropertiesset();
? ? ? ? ? ?valueoperations ops = redis.opsforvalue();
? ? ? ? ? ?testuser user1 = new testuser();
? ? ? ? ? ?user1.setname("lisi");
? ? ? ? ? ?user1.setid(20l);
? ? ? ? ? ?// ops.set("lisi", user1);
? ? ? ? ? ?testuser user = (testuser) ops.get("lisi");
? ? ? ? ? ?system.out.println(user.getname());
? ? ? ?} catch (exception e) {
? ? ? ? ? ?// todo auto-generated catch block
? ? ? ? ? ?e.printstacktrace();
? ? ? ?}
? ?}