Redis-12.在Java中操作Redis-Spring Data Redis使用方式-操作字符串类型的数据

一. 操作字符串类型的数据

java 复制代码
package com.sky.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

import java.util.concurrent.TimeUnit;

@SpringBootTest
public class SpringDataRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate() {
        System.out.println(redisTemplate);  // 首先输出redisTemplate对象看是否为空
        ValueOperations valueOperations = redisTemplate.opsForValue();  // redis当中的字符串类型数据操作对象
        HashOperations hashOperations = redisTemplate.opsForHash();     // redis当中的哈希类型数据操作对象
        ListOperations listOperations = redisTemplate.opsForList();     // redis当中的列表类型数据操作对象
        SetOperations setOperations = redisTemplate.opsForSet();        // redis当中的集合类型数据操作对象
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();     // redis当中的有序集合类型数据操作对象
    }

    @Test
    public void testString() {
        redisTemplate.opsForValue().set("city","北京");   // set
        String city = (String) redisTemplate.opsForValue().get("city");// get
        System.out.println(city);
        redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);     // setex
        redisTemplate.opsForValue().setIfAbsent("lock","1");   // setnx
        redisTemplate.opsForValue().setIfAbsent("lock","2");
    }
}

这里我们使用的是10号数据库,因为我们在配置文件中配置的是10号数据库。我们使用opsForValue()方法来对redis当中的字符串类型的数据进行操作。

1.使用set来进行redis数据库中字符串类型数据的添加

2.使用get查询redis数据库当中字符串类型数据的value

3.使用set(Object key, Object value, long timeout, TimeUnit unit)设置数据库中数据的过期时间,对应redis中的setex命令

4.使用setIfAbsent(Object key, Object value)设置数据库中的数据,如果不存在就加入数据库,如果存在就不加入,对应redis中的setnx命令

之后可以从数据库可视化工具中查看DB10号数据库中的数据内容:

redis当中get到的数据是Object类型的,因此要使用强制类型转换。此外,redis当中的String和Java当中的String有区别,因此会使得其在java当中get到的字符串和redis当中的字符串有区别,如在当前例子中Java中get到的是正常输入,而redis当中会乱码。 code不存在是因为该键值对已过期

lock当中存储的字符串1而不是2,那是因为使用setIfAbsent的话当数据库中的键已存在时,再插入同样键的新值不会生效。

相关推荐
欧哈东哥9 分钟前
【C++】标准库中用于组合多个值的数据结构pair、tuple、array...
java·数据结构·c++
python_13613 分钟前
web请求和响应
java·spring·github
ciku2 小时前
Spring AI Starter和文档解读
java·人工智能·spring
程序猿阿越2 小时前
Kafka源码(三)发送消息-客户端
java·后端·源码阅读
javadaydayup2 小时前
Apollo 凭什么能 “干掉” 本地配置?
spring boot·后端·spring
whitepure2 小时前
万字详解Java中的运算
java
AAA修煤气灶刘哥2 小时前
搞定 Redis 不难:从安装到实战的保姆级教程
java·redis·后端
MrSYJ2 小时前
全局和局部AuthenticationManager
java·后端·程序员