网站首页> 文章专栏> Springboot+Redis操作5种基本数据类型
Springboot+Redis操作5种基本数据类型
路人王 天津 199 0 0

1.springboot与普通的项目继承redis相比,只需要引入相关的启动器即可。我们引入redis的依赖。

        <!-- 自动版本控制,帮你引入了jedis客户端 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.编写测试程序

//k-v操作字符串的,用的比较多的。
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //k-v 对象的
    @Autowired
    RedisTemplate redisTemplate;

    //对象
    @Autowired
    RedisTemplate<Object, Employee> empRedisTemplate;

    /**       redis中常用的操作: 五大数据类型
     *     // String: stringRedisTemplate.opsForValue()
     *     // List:  stringRedisTemplate.opsForList()
     *     // Set: stringRedisTemplate.opsForSet()
     *     // Hash: stringRedisTemplate.opsForHash()
     *     // ZSet: stringRedisTemplate.opsForZSet()
     */

    @Test
    public void test01() {
        // 1.redis保存数据
        stringRedisTemplate.opsForValue().append("msg","hello");
        stringRedisTemplate.opsForValue().set("wang","12");

        // 2.redis读出数据
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.println(msg);

        // 3.redis操作列表  都一样 在命令行汇总找到就行
        stringRedisTemplate.opsForList().leftPush("mylist", "1");
        stringRedisTemplate.opsForList().leftPush("mylist", "2");
        stringRedisTemplate.opsForList().leftPush("mylist", "3");
    }


    // 2.redis测试保存对象,使用 redisTemplate
    // 2.存储一个对象,相对对象序列化 实现序列化 Serializable
    @Test
    public void test02() {
        Employee empById = employeeMapper.getEmpById(1);
        // 1.有乱码的方式
        redisTemplate.opsForValue().set("emp01",empById);

        // 2.可以以json的数据保存,自己把对象转换成json
        // redis有默认的序列化规则 改变默认的序列化规则
        empRedisTemplate.opsForValue().set("emp01", empById);
    }

评论

评论  分享  打赏