redisTemplate一opsForValue操作

当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。

Spring-data-redis的序列化类有下面这几个:GenericToStringSerializer: 可以将任何对象泛化为字符串并序列化;Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer实际上是一样的;JacksonJsonRedisSerializer: 序列化object对象为json字符串;JdkSerializationRedisSerializer: 序列化java对象(被序列化的对象必须实现Serializable接口);StringRedisSerializer: 简单的字符串序列化;GenericToStringSerializer:类似StringRedisSerializer的字符串序列化;GenericJackson2JsonRedisSerializer:类似Jackson2JsonRedisSerializer,但使用时构造函数不用特定的类参考以上序列化,自定义序列化类;

Spring Data JPA为我们提供了下面的Serializer:GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。

JdkSerializationRedisSerializer: 使用JDK提供的序列化功能。优点是反序列化时不需要提供类型信息(class),但缺点是需要实现Serializable接口,还有序列化后的结果非常庞大,是JSON格式的5倍左右,这样就会消耗redis服务器的大量内存。

Jackson2JsonRedisSerializer: 使用Jackson库将对象序列化为JSON字符串。优点是速度快,序列化后的字符串短小精悍,不需要实现Serializable接口。但缺点也非常致命,那就是此类的构造函数中有一个类型参数,必须提供要序列化对象的类型信息(.class对象)。 通过查看源代码,发现其只在反序列化过程中用到了类型信息。

key和hashKey:推荐使用     StringRedisSerializer: 简单的字符串序列化

hashValue:推荐使用     GenericJackson2JsonRedisSerializer:类似Jackson2JsonRedisSerializer,但使用时构造函数不用特定的类


/**

* redis配置类

*/

@Configuration

public class RedisConfig {


    @Bean

    @SuppressWarnings("all")

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {


        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式

        template.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式

        template.setHashKeySerializer(stringRedisSerializer);

        // value也采用String的序列化方式

        template.setValueSerializer(stringRedisSerializer);

        // hash的value序列化方式采用jackson

        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;


    }

}


//redisTemplate string类型数据读取 V get(Object key);

        redisTemplate.delete("hello");

        redisTemplate.opsForValue().set("hello","hello");

        System.out.println(redisTemplate.opsForValue().get("hello"));  //hello


        //加入失效机制 void set(K key, V value, long timeout, TimeUnit unit);

        redisTemplate.delete("world");

        redisTemplate.opsForValue().set("world", "world", 2, TimeUnit.SECONDS);

        Thread.sleep(1000);

        System.out.println(redisTemplate.opsForValue().get("world"));  //world

        Thread.sleep(1000);

        System.out.println(redisTemplate.opsForValue().get("world"));  //null


        //k v值是否与数据匹配 Boolean setIfAbsent(K key, V value);

        System.out.println(redisTemplate.opsForValue().setIfAbsent("hello","hello")); //true

        System.out.println(redisTemplate.opsForValue().setIfAbsent("world","world")); //false


        //为多个键赋值,取值

        //void multiSet(Map < ? extends K, ? extends V > map);

        //List multiGet(Collection < K > keys);

        //Boolean multiSetIfAbsent(Map< ? extends K, ? extends V > map);

        Map<String,String> map = new HashMap<String,String>();

        map.put("hello1","hello1");

        map.put("hello2","hello2");

        map.put("hello3","hello3");

        redisTemplate.opsForValue().multiSet(map);

        List<String> keys = new ArrayList<String>();

        keys.add("hello1");

        keys.add("hello2");

        keys.add("hello3");

        List<String> results = redisTemplate.opsForValue().multiGet(keys);

        for(String result :results){

            System.out.println(result);

        }

        map.put("hello4","hello4");

        System.out.println(redisTemplate.opsForValue().multiSetIfAbsent(map));  //false


        //设置新值并返回旧值 V getAndSet(K key, V value);

        System.out.println(redisTemplate.opsForValue().getAndSet("hello1","hello world")); //hello1

        System.out.println(redisTemplate.opsForValue().get("hello1")); //hello world


        redisTemplate.delete("hello6");

        //数据追加 Integer append(K key, String value);

        redisTemplate.opsForValue().set("hello6","hello");

        System.out.println(redisTemplate.opsForValue().get("hello6")); //hello

        Integer append = redisTemplate.opsForValue().append("hello6", "world");

        System.out.println(redisTemplate.opsForValue().get("hello6")); //helloworld


        //数据读取 String get(K key, long start, long end);

        System.out.println(redisTemplate.opsForValue().get("hello6",0,2)); //hel


        //获取字符串长度

        System.out.println(redisTemplate.opsForValue().size("hello6")); //10

}


/** 输出结果

hello

world

null

false

true

hello1

hello2

hello3

false

hello1

hello world

hello

helloworld

hel

10

*/


但是这里有一个坑

由于选择序列化器的原因 不能测试这段代码,需要测试的话可以将

// value序列化方式采用jackson

template.setValueSerializer(jackson2JsonRedisSerializer);


//整形数据增加 Long increment(K key, long delta);

//浮点型数据增加 Double increment(K key, double delta);

redisTemplate.opsForValue().set("hello5",1);

redisTemplate.opsForValue().increment("hello5",2);

System.out.println(redisTemplate.opsForValue().get("hello5")); //3

redisTemplate.opsForValue().increment("hello5",2.1);

System.out.println(redisTemplate.opsForValue().get("hello5")); //5.1


然而将序列化器修改之后,又会出来一个新的坑


redisTemplate.delete("hello6");

//数据追加 Integer append(K key, String value);

redisTemplate.opsForValue().set("hello6","hello");

System.out.println(redisTemplate.opsForValue().get("hello6")); //hello

Integer append = redisTemplate.opsForValue().append("hello6", "world");

System.out.println(redisTemplate.opsForValue().get("hello6")); //hello

//数据读取 String get(K key, long start, long end);

System.out.println(redisTemplate.opsForValue().get("hello6",0,2)); //"he

//获取字符串长度

System.out.println(redisTemplate.opsForValue().size("hello6")); //12

而且这里的append之后立刻读取的数据仍然是第一次设置的值。

而且如上图,hello6的值也会加上两个引号

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280