Offer

Redis--Springboot使用

Redis--springboot使用:

之前用redis是用命令行,现在整合到springboot做个简单使用:string,list,set,zset,hash,后面可能还要对redis分布式锁,秒杀项目,狂神说redis还要进一步做个总结

参考链接:https://blog.csdn.net/m0_37989980/article/details/107448418


Redis配置:

注意点:redis存储时如果不序列化和反序列化,对象就没法序列化存入(但是不写序列化配置就能存入)并且 存到redis就会乱码(不写序列化配置存入就乱码),配置共有两种,这次采用的代码,另一种就是redisconfig里面配置

  //修改 key值序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

Redis配置




Redis代码:

里面用到了两种redisTemplate和stringredisTemplate,两者是父子类,都可以使用5种类型的操作

package com.empirefree.springboot;

import com.alibaba.fastjson.JSONObject;
import com.empirefree.springboot.pojo.Content;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @program: springboot
 * @description: redisTest
 * @author: huyuqiao
 * @create: 2021/05/30 14:44
 */

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class RedisTests {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    public void testRedisKey(){
        //判断是否有key
        Boolean hasKey = stringRedisTemplate.hasKey("hyq");
        System.out.println(hasKey);

        //key对应value值的类型
        DataType dataType = stringRedisTemplate.type("obj");
        System.out.println(dataType);

        //获取redis所有key
        Set<String> keys =  stringRedisTemplate.keys("*");
//        keys.forEach(key -> System.out.println("key = " + key));

        //获取key超时时间: -1永不超时   -2key不存在  >=0过期时间
        Long expire = stringRedisTemplate.getExpire("hyq");
        System.out.println(expire);

        //获取一个随机的key
        System.out.println(stringRedisTemplate.randomKey());

        //修改key名字
        stringRedisTemplate.renameIfAbsent("hyq", "HYQ");
    }
    /*
    * description:操作redis中string类型
    * */
    @Test
    public void testString(){
        stringRedisTemplate.opsForValue().set("hyq", "胡宇乔", 120, TimeUnit.SECONDS);
        stringRedisTemplate.opsForValue().append("hyq", "往string中追加字符串");
        System.out.println(stringRedisTemplate.opsForValue().get("hyq"));
    }

    /*
     * description:操作redis中List类型
     * */
    @Test
    public void testList(){
        List<String> list = new ArrayList<>();
        list.add("name--A");
        list.add("name--B");
        stringRedisTemplate.opsForList().leftPush("list--hyq", "huyuqiao");
        stringRedisTemplate.opsForList().leftPushAll("list--hyq", list);

        List<String> stringList = stringRedisTemplate.opsForList().range("list--hyq", 0, -1);
        stringList.forEach(value -> System.out.println("value = " + value));
        System.out.println("=====");
        stringRedisTemplate.opsForList().trim("list--hyq", 1, 1);
    }

    /*
     * description:操作redis中set类型
     * */
    @Test
    public void testSet(){
        stringRedisTemplate.opsForSet().add("sets", "张三", "李四");
        Set<String> sets = stringRedisTemplate.opsForSet().members("sets");
        sets.forEach(value -> System.out.println("value = " + value));
        Long size = stringRedisTemplate.opsForSet().size("sets");
        System.out.println("stringRedisTemplate中set的size" + size);
    }

    /*
     * description:操作redis中zset类型  有序
     * */
    @Test
    public void testZset(){
        stringRedisTemplate.opsForZSet().add("zsets", "怎么玩1", 20);
        stringRedisTemplate.opsForZSet().add("zsets", "怎么玩2", 19);
        stringRedisTemplate.opsForZSet().add("zsets", "怎么玩3", 18);
        Set<String> zsets = stringRedisTemplate.opsForZSet().range("zsets", 0, -1);

        zsets.forEach(value -> System.out.println(value));
        Set<ZSetOperations.TypedTuple<String>> zsetsScore = stringRedisTemplate.opsForZSet().rangeByScoreWithScores("zsets", 0, 1000);
        zsetsScore.forEach(stringTypedTuple -> {
            System.out.println(stringTypedTuple.getValue());
            System.out.println(stringTypedTuple.getScore());
        });
    }

    /*
     * description:操作redis中hash类型
     * */
    @Test
    public void testHash(){
        //个人觉得有点类似Map<Key, Map<Key, value>>,感觉应该还是用string多一点,后面直接封装成Json就可以了
        stringRedisTemplate.opsForHash().put("maps", "name", "胡宇乔");
        stringRedisTemplate.opsForHash().putAll("maps", new LinkedHashMap<String, String>(){{
            put("age", "22");
            put("birthday", "2021-05-30");
        }});

        //得到key的多个key对应的value
        List<Object> values = stringRedisTemplate.opsForHash().multiGet("maps", Arrays.asList("name", "age"));
        values.forEach(value -> System.out.println(value));

        System.out.println("=====");
        String string = (String) stringRedisTemplate.opsForHash().get("maps", "name");
        System.out.println(string);
        List<Object> stringList =  stringRedisTemplate.opsForHash().values("maps");
        stringList.forEach(obj -> System.out.println(obj));
        Set<Object> keys =  stringRedisTemplate.opsForHash().keys("maps");
        keys.forEach(key -> System.out.println(key));
    }

    @Test
    public void testRedisTemplate(){
        //修改 key值序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        Content content = new Content();
        content.setImg(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set("content", content);

        Content content1 = (Content) redisTemplate.opsForValue().get("content");
        System.out.println(content1);

        redisTemplate.opsForList().leftPush("list", content);
        redisTemplate.opsForSet().add("set", content);
        redisTemplate.opsForZSet().add("zset", content, 10);
        redisTemplate.opsForHash().put("map", "name", content);
    }

    @Test
    public void testRedis(){
//        String k1 = stringRedisTemplate.opsForValue().get("k1");
//        log.info("拿到{}",k1);
        stringRedisTemplate.opsForValue().set("hyq", "huyuqiao");
        String hyq = stringRedisTemplate.opsForValue().get("hyq");
        log.info("RedisTests--testRedis: 得到redis值 {}", hyq);
        Content content = new Content();
        content.setTitle("胡宇乔");
        content.setPrice("22");
        content.setImg("Img");
        redisTemplate.opsForValue().set("obj", JSONObject.toJSONString(content));
        System.out.println(redisTemplate.opsForValue().get("obj"));
    }

}

posted @ 2021-05-30 16:23  Empirefree  阅读(71)  评论(0编辑  收藏  举报